简体   繁体   English

设置CORS不起作用

[英]Setting up CORS not working

I have the following headers set on the server 我在服务器上设置了以下标头

response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
response.addHeader("Access-Control-Allow-Headers","X-Custom-Header");

And i want to use the POST method to access a web service and send data to it but the problem is my setting up with the server is causing problems 而且我想使用POST方法来访问Web服务并向其中发送数据,但是问题是我在服务器上进行的设置引起了问题

I used the following method 我用下面的方法

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // XHR for Chrome/Safari/Firefox.
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        // CORS not supported.
        xhr = null;
    }
    return xhr;
}

and based on this object 并基于此对象

url = "http://myurl.do";
var xhr = createCORSRequest('POST', url);
if (!xhr) {
    alert('CORS not supported');
    return;
}
var params = "name=pari123&action=initaction&gameId=slotreel3";
xhr.setRequestHeader('Content-Type', 'application/text/plain'); 
if(xhr.readyState == 4 && xhr.status == 200) 
{
    alert('Tested OK')
    xhr.send(params);
}
else
{
    alert('status not 200 or xhr is not ready');
}

// Response handlers.
xhr.onload = function() {
    var text = xhr.responseText;
    alert('Response from CORS request to ' + url + ': ' + text);
};

xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
};

But always it alerts a message saying 'status not 200 or xhr is not ready' i am not able to proceed any one if you know please kindly help! 但是总是会提示“状态不是200或xhr尚未准备好”的消息,如果您知道请帮忙,我将无法继续进行任何操作!

when i print the xhr.readyState its printing a value of 1 当我打印xhr.readyState其打印值为1

if(xhr.readyState == 4 && xhr.status == 200) 

This check must be placed in the onreadystatechange event handler. 此检查必须放在onreadystatechange事件处理程序中。 You obviously cannot have a 200 status code or a "finished" request before actually sending it. 显然,在实际发送之前,您不能有200状态代码或“完成”的请求。

What you wanted is probably this: 您想要的可能是这样的:

xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert('Tested OK');
        var text = xhr.responseText;
        alert('Response from CORS request to ' + url + ': ' + text);
    }
};
xhr.send(params);

If you want an else case to check for errors remember that you still need to check for xhr.readyState == 4 . 如果您想让else情况检查错误,请记住,您仍然需要检查xhr.readyState == 4 You don't want your error-handling code to run for other readyStates. 您不希望为其他readyState运行错误处理代码。

There is no need for the onload event - when you get readyState == 4 you know the request has finished. 不需要onload事件-当您获得readyState == 4您就知道请求已完成。

There can be several issues here. 这里可能有几个问题。

I observed that different browsers implement CORS differently. 我观察到不同的浏览器对CORS的实现方式有所不同。 My experience is based on Firefox and Google Chrome. 我的经验是基于Firefox和Google Chrome。 For example, I had to add a special header on server side, so that Firefox would make the preflight (OPTIONS) request and the actual request (GET,PUT etc.) using one connection as Google Chrome does it. 例如,我必须在服务器端添加一个特殊的标头,以便Firefox可以像Google Chrome那样使用一个连接发出预检(OPTIONS)请求和实际请求(GET,PUT等)。 You would have to add on the server side: 您将必须在服务器端添加:

response.addHeader("Keep-Alive", "timeout=2, max=100");
response.addHeader("Connection", "Keep-Alive");

I also noticed that some browsers do not like the wildcard ("*") in the CORS headers. 我还注意到某些浏览器不喜欢CORS标头中的通配符(“ *”)。 A workaround for the line 该生产线的解决方法

response.addHeader("Access-Control-Allow-Origin", "*");

would be to return the origin of the request and not a wildcard. 将返回请求的来源,而不是通配符。

However, there could be also other problems and we would need more details. 但是,还可能存在其他问题,我们需要更多详细信息。 For example, does the request work when the server is hosted on the same domain (ie the problem might not be related to CORS). 例如,当服务器托管在同一域上时,请求是否起作用(即问题可能与CORS无关)。 What server are you using? 您正在使用什么服务器?

xhr.send(); needs to be just after the call to xhr.open(); 需要xhr.open();的调用之后xhr.open(); does it not? 不是吗 Status 1 means the request has not been sent yet, it'll never get to status 4 unless you actually send the request.. 状态1表示请求尚未发送,除非您实际发送请求,否则它将永远不会进入状态4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM