为什么我会收到错误'Access Control Allow Origin不允许'在我使用setRequ

Why do I get the error 'not allowed by Access-Control-Allow-Origin' after I use setRequestHeader?

本文关键字:Origin 不允许 setRequ Allow Control 错误 为什么 Access      更新时间:2023-09-26

搜索了一段时间后,我还找不到答案。我的问题是,当我调用web服务函数setRequestHeader时,我得到了错误"Access Control Allow Origin不允许"。

这是我的javaScript代码:

var loginController = new sap.ltst.login.loginController({controllerName: "sap.ltst.login.loginController"});
var session = loginController.login("I051486", "123456789");
var config = {};
$.ajax({
    beforeSend: function(req) {
        req.setRequestHeader('Authentication', 'Authentication-Token ' + session.session_token);
    },
    url : "http://localhost:8081/com.sap.st.gtpapi/program/"
            + this.program + "/configs",
    dataType : 'json',
    type : 'GET',
    async : false,
    success : function(data) {
        config = data;
    }
});
return config;

在web服务端,我有一个功能,我可以启用或禁用身份验证。我试图将auth设置为false(不检查auth),然后删除setRequestHeader,我没有得到错误,web服务返回了一些数据。

用另一种方式,我试着把它放回去,我得到了错误。

 XMLHttpRequest cannot load http://localhost:8081/gtpapi/program/Business%20Intelligence%20platform%204.1%20(BI%20Aurora%204.1)/configs. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. 

所以我不认为这是身份验证的问题,因为在web服务端,我禁用了身份验证。

让我们转到web服务端,这是接口:

    public static final String HEADER_AUTH_TOKEN = "Authentication-Token";
    @GET
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    @Path("/guid_{planId}/packages/{packId}/{results}")
    public Response setPackageResult(@PathParam("planId") final String planGuid,    @PathParam("packId") final String packGuid, @PathParam("results") final String results, @HeaderParam(WebServiceBase.HEADER_AUTH_TOKEN) String token);

这是Chrome上的头响应et请求:

Request       URL:http://localhost:8081/com.sap.st.gtpapi/program/SBOP%20EXPLORER%204.1/configs
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:UTF-8,*;q=0.5
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Access-Control-Request-Headers:accept, authentication, origin
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8081
Origin:http://localhost:8080
Pragma:no-cache
Referer:http://localhost:8080/LTST_Frontend/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Response Headersview source
Allow:GET,OPTIONS,HEAD
Content-Length:0
Content-Type:text/xml
Date:Fri, 02 Aug 2013 15:44:10 GMT
Server:Apache-Coyote/1.1

我不确定我是否犯了一些错误,无论问题是来自javaScript还是web服务。有什么想法吗?

将要发送的任何标头放入安全列表:

header("Access-Control-Allow-Headers: Authentication, X-Custom-Header, .. etc");

这应该是接收域上CORS标头的一部分。