所以我有一个基于Java EE的REST服务,它除了设置CORS标题之外还返回带有此函数的每个请求:
protected Response.ResponseBuilder addRequiredHeaders(Response.ResponseBuilder rb) {
return rb
.header("Access-Control-Allow-Origin", "http://localhost:8080")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE")
.header("Access-Control-Allow-Headers", "Content-Type, *");
}
现在当我从前端提出请求时,我仍然遇到一些与CORS相关的问题。这是来自前端
的请求的代码fetch (apiURL + "/api/rest/users/create", {
body: JSON.stringify(payload),
headers: {
"content-type": "application/json"
},
method: "POST",
mode: "cors",
})
.then((response) => {
...
}.catch((err) => {
...
}
以下是确切的错误消息:
Failed to load http://localhost:8888/java_ee_project/api/rest/users/create:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
以下是来自浏览器的devtools中的网络选项卡的一些其他信息
General
Request URL: http://localhost:8888/java_ee_project/api/rest/users/create
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: 127.0.0.1:8888
Referrer Policy: no-referrer-when-downgrade
Response Headers
Allow: POST, OPTIONS
Connection: keep-alive
Content-Length: 13
Content-Type: text/plain;charset=UTF-8
Date: Fri, 04 May 2018 23:10:04 GMT
Server: WildFly/11
X-Powered-By: Undertow/1
Request Headers
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
DNT: 1
Host: localhost:8888
Origin: http://localhost:8080
Referer: http://localhost:8080/
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1
当我与Postman执行相同的请求时,一切正常,所以我很乐意提供有关此问题的任何帮助或信息。
答案 0 :(得分:0)
通过添加的responsebuilder功能以某种方式解决方案无法正常工作。
使用http://www.codingpedia.org/ama/how-to-add-cors-support-on-the-server-side-in-java-with-jersey/中的第二个选项和cors响应过滤器,它现在正在运行。