0

搜索了一段时间后,我还没有找到答案。我的问题是当我调用 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 服务方面,我有一个可以启用或禁用身份验证的功能。我尝试将身份验证设置为 false(不检查身份验证)然后删除 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 上的标头响应和请求:

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 服务,我犯了一些错误。有任何想法吗?

4

1 回答 1

0

Put any header you want to send in the safe list:

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

This should be part of the CORS headers on the receiving domain.

于 2013-08-02T14:38:17.477 回答