【发布时间】:2017-09-30 20:59:42
【问题描述】:
我正在尝试从在浏览器上运行的代码(通过插件)获取各种 .js 文件的内容。
使用XMLHttpRequest 获取驻留在同一服务器上的 .js 文件没有问题,但是当我需要获取其他域上的 .js 文件的内容时,我正在尝试使用 CORS 但我不能似乎无法正常工作
这是我的代码
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
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;
}
// Make the actual CORS request.
function makeCorsRequest(url) {
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
return xhr.responseText;
};
xhr.onerror = function() {
alert('There was an error making the request.');
};
xhr.send();
}
当我跑步时:
url = `https://......./javascript.js'
res = makeCORSTRequest(url)
我收到“发出请求时出错。”错误警报和控制台日志
XMLHttpRequest 无法加载 https://......./javascript.js。不 请求中存在“Access-Control-Allow-Origin”标头 资源。 Origin 'https://.....com' 因此不允许访问。
【问题讨论】:
标签: javascript xmlhttprequest cors