【发布时间】:2020-03-28 21:21:30
【问题描述】:
意图:
在 Angular 中使用通过基于 SpringMVC 的 Web 应用程序公开的 REST API。两者都在不同的主机上运行
问题:
虽然我请求的 API 是 GET 请求,但 Angular幕后首先向 REST API SpringMVC 服务器发出 OPTIONS 请求。这会引发 500 服务器错误(请参阅下面的 CURL 输出)。
尝试使用 Postman 工具 (GET 请求) 访问相同的 API,令人惊讶的是它提供了所需的输出 (即也提供了 Access-Control-Allow-Origin 标头) 没有任何错误,但 OPTIONS 请求引发 500 服务器错误。
我正在使用的技术栈:
-
Angular 6(在NodeJS上运行) -
Spring MVC 4.3.6.RELEASE(no Spring 安全明确配置)[Java config 基于 Spring 配置] -
Jetty-Runner 9.4.1(运行 Spring MVC webapp 的 WAR 文件)。
Angular 收到的错误消息:
Access to XMLHttpRequest at 'http://localhost:8080/v1/create' from origin
'http://localhost:4200' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested resource.
代码片段:
Angular 代码:
public createDomainObj() {
return this.http.post('http://localhost:8080/v1/create', request body parameter)
}
SpringMVC 代码:
@ResponseBody
@RequestMapping(value = "/v1/create", method = RequestMethod.POST)
@AccessController(accessLevel = "Anonymous")
public <APIResponseModelClass> anAPIMethod(@RequestBody param1, param2) {
//code logic
return <obj>;
}
已经尝试过的内容:
SpringMVC 中的 CORS 过滤器,所有注释组合,但没有运气。
也尝试过以下链接中提到的建议,但均未成功:
https://www.baeldung.com/spring-security-cors-preflight
How to add Access-Control-Allow-Origin to jetty server
CURL 能够重现问题:
请求:
curl -H "Origin:*" -H "Access-Control-Request-Method: GET, POST, PUT, DELETE"
-H "Access-Control-Request-Headers: X-Requested-With"
-X OPTIONS --verbose http://localhost:8080/v1/create
回应:
Trying 127.0.0.1...
Connected to localhost (127.0.0.1) port 8080 (#0)
OPTIONS /v1/create HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.47.0
Accept: */*
Origin:*
Access-Control-Request-Method: GET, POST, PUT, DELETE
Access-Control-Request-Headers: X-Requested-With
Content-Length: 392
Content-Type: application/x-www-form-urlencoded
upload completely sent off: 392 out of 392 bytes
HTTP/1.1 500 Server Error
Connection: close
Server: Jetty(9.4.2.v20170220)
Closing connection 0
那么,如何让 Angular 使用 SpringMVC 中具有 OPTIONS 预检方面的 REST API?
【问题讨论】:
-
您在使用
spring-security吗?尝试阅读spring.io/guides/gs/rest-service-cors -
你能添加你失败的代码吗??
标签: java spring-mvc cors angular6 preflight