我正在使用spring MVC和angular 7创建一个CRUD应用程序。 我已经在我的spring应用程序中允许使用CORS,但是当我从angular调用PUT请求时,我收到一个“从原点“ http://localhost:8080/BookAPI/api/updateBook/70”到“ http://localhost:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上没有“ Access-Control-Allow-Origin”标头”错误
我已在spring-mvc应用程序中启用了CORS
package com.book.spring.controller;
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/';
它应该允许所有请求
答案 0 :(得分:1)
经过两天的过多搜索。终于找到答案了!!
这是 IIS 本身的问题 WebDAVModule 似乎默认阻止 PUT 和 DELETE 方法!
<system.webServer>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
</system.webServer>
我真的希望没有其他人为此感到痛苦! =]
答案 1 :(得分:0)
尝试在API响应中设置“ Access-Control-Allow-Methods”标头,以允许PUT请求。
答案 2 :(得分:0)
您应该使用this._http.put进行放置请求,您不应将post client用于放置请求。
更改
返回 this._http.post (this._putBookUrl + book.id,{“标题”:book.title,“作者”:book.author},{responseType:“文本”, headers:headers}) .pipe(catchError(this.errorHandlerPost));
至 返回 this._http.put (this._putBookUrl + book.id,{“ title”:book.title,“ author”:book.author},{responseType:'text',headers:headers }) .pipe(catchError(this.errorHandlerPost));