javascript 是否可以跨域使用 XMLHttpRequest

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8524052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:43:11  来源:igfitidea点击:

Is it possible to use XMLHttpRequest across Domains

javascriptajaxbrowsercross-domain

提问by Javanerd

Cross Site XMLHttpRequest from JavaScript can it be done?

来自 JavaScript 的跨站点 XMLHttpRequest 可以做到吗?

I understand the limitations and why it is not generally able to work, but as of firefox 3.5 there is the

我了解限制以及为什么它通常无法正常工作,但是从 Firefox 3.5 开始,有

Access-Control-Allow-Origin: *

Access-Control-Allow-Origin: *

which is supposed to allow this to work.

这应该允许它工作。

It tells the browser that the server does not care if the request is sent to it from a domain that did not serve the page.

它告诉浏览器服务器不关心请求是否是从不提供页面服务的域发送给它的。

The code I am using is below.

我正在使用的代码如下。

function sendData(webservicePayload, callbackFunction) {
var request = null;
if (!window.XMLHttpRequest) { // code for IE
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (E) {
            return 'Create XMLHTTP request IE';
        }
    }
} else { // code for Mozilla, etc.
    request = new XMLHttpRequest();
}
/*
 * Setup the callback function
 */
request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status < 300) {
        eval(callbackFunction);
    }
};
if (!request) {
    nlapiLogExecution('ERROR', 'Create XMLHTTP request', 'Failed');
    return;
}
/*
 * Setup the request headers
 */

request.open('POST','http://www.another.domain.co.uk/webservice.asmx', true);
request.setRequestHeader('Man','POST http://www.another.domain.co.uk/webservice.asmx HTTP/1.1');
request.setRequestHeader('MessageType', 'CALL');
request.setRequestHeader('Content-Type', 'text/xml; charset="utf-8"');
request.setRequestHeader('Cache-Control', 'no-cache');
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

request.setRequestHeader('SOAPAction','http://www.another.domain.co.uk/WebService/eService');
request.send(webservicePayload);

}

}

This is sending the correct request header

这是发送正确的请求标头

REQUEST

要求

OPTIONS /webservice.asmx HTTP/1.1
Host: www.another.domain.co.uk
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Origin: https://my.domain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: cache-control,content-type,man,messagetype,soapaction
Pragma: no-cache
Cache-Control: no-cache

and receiving an expected response header

并收到预期的响应标头

RESPONSE

回复

HTTP/1.1 403 Forbidden
Server: Microsoft-IIS/5.1
Date: Wed, 14 Dec 2011 13:43:27 GMT
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Connection: close
Content-Type: text/html
Content-Length: 44

As you can see the Orgin is specified in the request and the server responds with acceptance of any ("*") domain.

如您所见,请求中指定了 Orgin,服务器响应接受任何(“*”)域。

Why am I getting "Forbidden 403" as I feel that everything I have done is correct, I can't work out why?

为什么我会收到“Forbidden 403”,因为我觉得我所做的一切都是正确的,我不知道为什么?

Is anyone else getting this?

有其他人得到这个吗?

Do you know what is causing it?

你知道是什么原因造成的吗?

回答by monsur

A CORs request actually consists of two physical HTTP requests: 1) The preflight request, and 2) the actual request. The request you posted above looks like the preflight request, since it is uses the HTTP OPTIONS method. So the first thing you have to do is verify that your server accepts OPTIONS requests (I believe this should just work, but it may explain why you are receiving a 403).

一个 COR 请求实际上由两个物理 HTTP 请求组成:1) 预检请求,以及 2) 实际请求。您在上面发布的请求看起来像预检请求,因为它使用 HTTP OPTIONS 方法。因此,您必须做的第一件事是验证您的服务器是否接受 OPTIONS 请求(我相信这应该可以正常工作,但它可以解释为什么您会收到 403)。

Next, you need a valid preflight response. The response to a preflight request must also contain the following two headers:

接下来,您需要一个有效的预检响应。对预检请求的响应还必须包含以下两个标头:

Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Origin,cache-control,content-type,man,messagetype,soapaction

(See how these response headers are an echo of the Access-Control-Request-Method and Access-Control-Request-Headers request headers). The Access-Control-Allow-Headers header should contain any custom request headers.

(了解这些响应标头如何与 Access-Control-Request-Method 和 Access-Control-Request-Headers 请求标头相呼应)。Access-Control-Allow-Headers 标头应包含任何自定义请求标头。

Once the browser receives this response, it knows that the preflight request has been accepted, and it makes the actual request. On the actual request, you only need the following header:

一旦浏览器收到此响应,它就知道预检请求已被接受,并发出实际请求。在实际请求中,您只需要以下标头:

Access-Control-Allow-Origin: *

You can learn more about preflight requests and handling CORS requests here: http://www.html5rocks.com/en/tutorials/cors/

您可以在此处了解有关预检请求和处理 CORS 请求的更多信息:http: //www.html5rocks.com/en/tutorials/cors/