有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript无法设置“AccessControlAllowOrigin”标题

我需要从react应用程序远程访问我的web api。在服务器端,我做了以下操作以允许跨域通信:

import javax.ws.rs.core.Response;
import com.mypackage.ResponseDto;

@Override
public Response fetch(String id, String env) throws ServiceException
{ 
     ResponseDto res = new ResponseDto();
     res = updateResp(id, env); // not important

     return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}

当我从邮递员处查看时,我可以看到cors标题正确设置如下:

access-control-allow-origin →*
content-type →application/json
date →Wed, 16 Aug 2017 11:07:16 GMT
server →web
transfer-encoding →chunked

但当我从react应用程序访问同一个端点时,浏览器开始抱怨以下错误:

Fetch API cannot load http://myservices.com/myservice-app/services/. 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:3000' 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

知道这是怎么回事吗

编辑#1 以下更改是否仍看到相同的错误:

return Response.ok()
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
            .header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
            .entity(response).build();

共 (0) 个答案