我正在尝试编写一个函数,它对图像进行get请求,并在失败/ catch时执行一些DOM操作。我原来把它写成:
function SynchronousHttpGetRequestAndClearDomIdsOnFail(resourceUrl, domIds)
{
try {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", resourceUrl, false); // false for synchronous request
xmlHttp.send(null);
return xmlHttp.responseText;
}
catch (httpGetError) {
console.log("got HTTP GET error:" + httpGetError);
for (var i = 0; i<domIds.length; i++){
domConstruct.empty(domIds[i]);
}
}
}
然后我收到以下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3340' is therefore not allowed access.
所以,然后我在.open之后立即更改了函数以包含setRequestHeader:
function SynchronousHttpGetRequestAndClearDomIdsOnFail(resourceUrl, domIds)
{
try {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", resourceUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "http://localhost:3340");
xmlHttp.send(null);
return xmlHttp.responseText;
}
catch (httpGetError) {
console.log("got HTTP GET error:" + httpGetError);
for (var i = 0; i<domIds.length; i++){
domConstruct.empty(domIds[i]);
}
}
}
我仍然收到了另一个类似的错误:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3340' is therefore not allowed access.
因此,我看了一下通过网络发送的标题:
OPTIONS /Sheets/MAIN_007.bmp HTTP/1.1
Host: cloudserver01.spatialserver.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost.com:3340
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
Access-Control-Request-Headers: access-control-allow-origin
Accept: */*
Referer: http://localhost:3340/webappbuilder/apps/3/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,de;q=0.6
为什么没有正确设置/发送Access-Control-Request-Headers?
感谢您的时间。