【发布时间】:2013-12-02 21:07:27
【问题描述】:
我在服务器上设置了以下标头
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
response.addHeader("Access-Control-Allow-Headers","X-Custom-Header");
我想使用 POST 方法访问 Web 服务并向其发送数据,但问题是我与服务器的设置导致了问题
我使用了以下方法
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;
}
并基于此对象
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.');
};
但它总是提醒一条消息说“状态不是 200 或 xhr 未准备好”我无法继续任何人如果你知道请帮忙!
当我打印 xhr.readyState 时,它的打印值为 1
【问题讨论】:
-
我正在使用 MAMP 运行文件
-
您的服务器端代码看起来不一致:您混淆了逗号和冒号。可以吗?
-
response.addHeader("Access-Control-Allow-Methods","GET, POST, PUT");
标签: javascript cors