获得;“被CORS政策阻止”;仅来自angular 7的PUT请求出错
我正在使用SpringMVC和angular 7创建一个CRUD应用程序。 我在spring应用程序中允许CORS,但当我从angular调用PUT请求时,我得到一个“从源站“”访问“”处的XMLHttpRequest已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源站”标头”错误 我已经在spring mvc应用程序中启用了CORS 包com.book.spring.controller获得;“被CORS政策阻止”;仅来自angular 7的PUT请求出错,angular,spring-mvc,cors,Angular,Spring Mvc,Cors,我正在使用SpringMVC和angular 7创建一个CRUD应用程序。 我在spring应用程序中允许CORS,但当我从angular调用PUT请求时,我得到一个“从源站“”访问“”处的XMLHttpRequest已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源站”标头”错误 我已经在spring mvc应用程序中启用了CORS 包com.book.spring.controller import java.util.List; import
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/';
import java.util.List;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.http.ResponseEntity;
导入org.springframework.web.bind.annotation.CrossOrigin;
导入org.springframework.web.bind.annotation.DeleteMapping;
导入org.springframework.web.bind.annotation.GetMapping;
导入org.springframework.web.bind.annotation.PathVariable;
导入org.springframework.web.bind.annotation.PostMapping;
导入org.springframework.web.bind.annotation.PutMapping;
导入org.springframework.web.bind.annotation.RequestBody;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RestController;
导入com.book.spring.models.book;
导入com.book.spring.service.BookService;
@交叉原点(“*”)
@请求映射(“/api”)
@RestController
公共类图书管理员{
@自动连线
私人图书服务;
//保存一本书
@后映射(“/create”)
公共响应性createBook(@RequestBody Book){
Long bookId=bookService.create(book);
return ResponseEntity.ok().body(“使用ID=“+bookId”创建的书);
}
//拿到所有的书
@GetMapping(“/getBooks”)
公众反应清单{
List=bookService.getAllBooks();
返回ResponseEntity.ok().body(列表);
}
//按ID取一本书
@GetMapping(“/getBookByID/{id}”)
公共响应getBookById(@PathVariable(“id”)长id){
BookBook=bookService.getBookById(id);
返回ResponseEntity.ok().body(book);
}
//更新一本书
@PutMapping(“/updateBook/{id}”)
public ResponseEntity updateBook(@PathVariable(“id”)长id,@RequestBody Book){
bookService.updateBook(id,book);
返回ResponseEntity.ok().body(“书籍更新”);
}
//删除一本书
@DeleteMapping(“/deleteBook/{id}”)
公共响应属性deleteBook(@PathVariable(“id”)长id){
bookService.deleteBook(id);
return ResponseEntity.ok().body(“书籍已被删除”);
}
}
bookservice.ts:
从“@angular/core”导入{Injectable};
从“/URL”导入*作为URL常量;
从'@angular/common/http'导入{HttpClient,HttpErrorResponse,HttpHeaders};
从“rxjs”导入{observatable,throwerr};
从“./Book/Book”导入{Book};
从“rxjs/operators”导入{catchError};
const headers=新的HttpHeaders({
“内容类型”:“应用程序/json”,
“访问控制允许来源”:“*”
});
@注射的({
providedIn:'根'
})
出口类图书服务{
private\u getBooksUrl:string=urlstants.BOOKS\u URL;
private\u postBooksUrl:string=urlstants.POST\u BOOK\u URL;
private\u deleteBooksUrl:string=urlstants.DELETE\u BOOK\u URL;
private\u getBookUrl:string=urlstants.GET\u BOOK\u URL;
private\u putBookUrl:string=urlstants.PUT\u BOOK\u URL;
构造函数(私有的_http:HttpClient){}
getAllBooks():可观察{
console.log(this.\u getBooksUrl);
返回此。_http.get(此。_getBooksUrl)
.pipe(catchError(this.errorHandler));
}
addBook(book:book){
控制台日志(“添加簿”);
if(book.id){
返回此。_http.post(此。_putBookUrl+book.id,{“title”:book.title,“author”:book.author},{responseType:'text',headers:headers})
.pipe(catchError(this.errorHandlerPost));
}否则{
返回此.http.post(此.postBooksUrl,book,{responseType:'text'})
.pipe(catchError(this.errorHandlerPost));
}
}
deleteBook(id:string){
返回此。_http.delete(此。_deleteBooksUrl+id,{responseType:'text'})
.pipe(catchError(this.errorHandlerPost));
}
getBookById(bookId:string):可观察{
返回此。_http.get(此。_getBookUrl+bookId)
.pipe(catchError(this.errorHandlerPost));
}
errorHandler(errorHandler:HttpErrorResponse):可观察{
返回抛出器错误(errorHandler.message | |“服务器错误”);
}
errorHandlerPost(errorHandler:HttpErrorResponse){
返回抛出器错误(errorHandler.message | |“服务器错误”);
}
}
常数:
导出常量图书http://localhost:8080/BookAPI/api/getBooks';
导出const POST\u BOOK\u URL='1http://localhost:8080/BookAPI/api/create';
导出常量删除\u BOOK\u URL='0http://localhost:8080/BookAPI/api/deleteBook/';
导出const GET\u BOOK\u URL='0http://localhost:8080/BookAPI/api/getBookByID/';
导出const PUT\u BOOK\u URL='1http://localhost:8080/BookAPI/api/updateBook/';
它应该允许所有请求尝试将API响应中的“Access Control allow Methods”头设置为允许PUT请求。您应该使用它。_http.PUT for PUT request,您不应该使用post client for PUT request 更改自 返回this.\u http.post(this.\u putBookUrl+book.id,{“title”:book.title,“author”:book.author},{responseType:'text',headers:headers}) .pipe(catchError(this.errorHandlerPost)) 至 返回this.\u http.put(this.\u putBookUrl+book.id,{“title”:book.title,“author”:book.author},{responseType:'text',headers:headers})
.pipe(catchError(this.errorHandlerPost)) 经过两天太多的搜索。我终于找到了答案 这是IIS本身的问题 WebDAVModule,默认情况下,它似乎会阻止PUT和DELETE方法
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
我真的希望没有其他人p