首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只有来自angular 7的PUT请求出现"blocked blocked blocked policy“错误

只有来自angular 7的PUT请求出现"blocked blocked blocked policy“错误
EN

Stack Overflow用户
提问于 2019-05-20 19:44:12
回答 3查看 1.7K关注 0票数 0

我正在使用spring MVC和angular 7创建一个CRUD应用程序。我在spring应用程序中允许CORS,但是当我从angular调用PUT请求时,我得到一个“从原始资源'http://localhost:4200‘访问位于'http://localhost:8080/BookAPI/api/updateBook/70’的XMLHttpRequest被CORS策略阻止:对印前检查请求的响应没有通过访问控制检查:请求的资源上没有' access - control -Allow- origin‘头”错误

我已经在spring-mvc应用程序中启用了CORS

打包com.book.spring.controller;

代码语言:javascript
复制
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.book.spring.models.Book;
import com.book.spring.service.BookService;
@CrossOrigin("*")
@RequestMapping("/api")
@RestController
public class BookController {
    @Autowired
    private BookService bookService;

    // Save a book
    @PostMapping("/create")
    public ResponseEntity<String> createBook(@RequestBody Book book) {
        Long bookId = bookService.create(book);
        return ResponseEntity.ok().body("Book created with ID =" + bookId);
    }

    // Get All books
    @GetMapping("/getBooks")
    public ResponseEntity<List<Book>> listbooks() {
        List<Book> list = bookService.getAllBooks();
        return ResponseEntity.ok().body(list);
    }

    // Get a book by its ID
    @GetMapping("/getBookByID/{id}")
    public ResponseEntity<Book> getBookById(@PathVariable("id") Long id) {
        Book book = bookService.getBookById(id);
        return ResponseEntity.ok().body(book);
    }

    // Update a book
    @PutMapping("/updateBook/{id}")
    public ResponseEntity<?> updateBook(@PathVariable("id") Long id, @RequestBody Book book) {
        bookService.updateBook(id, book);
        return ResponseEntity.ok().body("Book updated");
    }

    // Delete a book
    @DeleteMapping("/deleteBook/{id}")
    public ResponseEntity<?> deleteBook(@PathVariable("id") Long id) {
        bookService.deleteBook(id);
        return ResponseEntity.ok().body("Book has be deleted");
    }
}


bookservice.ts:
import { Injectable } from '@angular/core';
import * as UrlConstants from './urls';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { Book } from './book/book';
import { catchError } from 'rxjs/operators';

const headers = new HttpHeaders({ 
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin':'*'
});  
@Injectable({
  providedIn: 'root'
})
export class BookService {
  private _getBooksUrl: string = UrlConstants.BOOKS_URL;
  private _postBooksUrl: string = UrlConstants.POST_BOOK_URL;
  private _deleteBooksUrl: string = UrlConstants.DELETE_BOOK_URL;
  private _getBookUrl: string = UrlConstants.GET_BOOK_URL;
  private _putBookUrl: string = UrlConstants.PUT_BOOK_URL;
  constructor(private _http: HttpClient) { }
  getAllBooks(): Observable<Book[]> {
    console.log(this._getBooksUrl);
    return this._http.get<Book[]>(this._getBooksUrl)
      .pipe(catchError(this.errorHandler));
  }

  addBook(book: Book) {
    console.log("adding book");
    if (book.id) {
      return this._http.post(this._putBookUrl + book.id, {"title":book.title,"author":book.author}, { responseType: 'text',headers:headers})
        .pipe(catchError(this.errorHandlerPost));
    } else {
      return this._http.post(this._postBooksUrl, book, { responseType: 'text' })
        .pipe(catchError(this.errorHandlerPost));
    }
  }

  deleteBook(id: string) {
    return this._http.delete(this._deleteBooksUrl + id, { responseType: 'text' })
      .pipe(catchError(this.errorHandlerPost));
  }


  getBookById(bookId: string): Observable<Book> {
    return this._http.get<Book>(this._getBookUrl + bookId)
      .pipe(catchError(this.errorHandlerPost));
  }
  errorHandler(errorHandler: HttpErrorResponse): Observable<Book[]> {
    return throwError(errorHandler.message || "server error");
  }
  errorHandlerPost(errorHandler: HttpErrorResponse) {
    return throwError(errorHandler.message || "server error");
  }
}


consts:
export const BOOKS_URL = 'http://localhost:8080/BookAPI/api/getBooks';
export const POST_BOOK_URL = 'http://localhost:8080/BookAPI/api/create';
export const DELETE_BOOK_URL ='http://localhost:8080/BookAPI/api/deleteBook/';
export const GET_BOOK_URL ='http://localhost:8080/BookAPI/api/getBookByID/';
export const PUT_BOOK_URL = 'http://localhost:8080/BookAPI/api/updateBook/';

它应该允许所有请求

EN

回答 3

Stack Overflow用户

发布于 2021-01-21 21:31:56

经过两天太多的搜寻。我终于找到答案了!

这是IIS本身的一个问题,WebDAVModule在默认情况下似乎阻塞了PUT和DELETE方法!

代码语言:javascript
复制
<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

我真的希望没有其他人为此感到痛苦!=]

字体:https://mozartec.com/asp-net-core-error-405-methods-not-allowed-for-put-and-delete-requests-when-hosted-on-iis/

票数 1
EN

Stack Overflow用户

发布于 2019-05-20 20:11:38

尝试将API响应中的“Access-Control- allow -Methods”标头设置为允许PUT请求。

票数 0
EN

Stack Overflow用户

发布于 2019-12-18 19:38:00

put请求应该使用this._http.put,put请求不应该使用post客户端。

来自的更改

this._http.post(this._putBookUrl + book.id,{"title":book.title,“:book.author”:book.author},{ responseType:'text',headers:headers}) .pipe(catchError(this.errorHandlerPost));

标题返回this._http.put(this._putBookUrl +,{“”book.id,“:book.title”:book.author},{ responseType:‘’,headers:headers}) .pipe(catchError(this.errorHandlerPost));

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56220351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档