【发布时间】:2017-04-14 11:50:45
【问题描述】:
我正在使用 Webpack 来捆绑我的 javascript 代码并在浏览器中使用模块。
我正在尝试获取 URL 的正文 (http://www.redbubble.com);但是,我收到以下错误:
XMLHttpRequest cannot load http://www.redbubble.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
这是我捆绑的代码,并请求获取http://www.redbubble.com 的正文 html(包括在我的 ejs 中的脚本标记参考下)
var request = require('request');
var options = {
url: 'http://www.redbubble.com',
withCredentials: false
};
function callback(error, response, body) {
window.console.log("callback is being called");
if (!error && response.statusCode == 200) {
alert(body);
} else {
window.console.log(error);
}
}
request(options, callback);
我也在尝试使用我的 app.js 中的 CORS 模块来解决 Acces-Control-Allow-Origin 错误,但这并不好。
app.use(cors({
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false
}));
为什么这个错误仍然存在?又该如何解决?
【问题讨论】:
-
"我也在尝试在我的 app.js 中使用 CORS 模块" — 您的
app.js正在localhost:3000上运行,而不是在www.redbubble.com上运行 -
@Quentin 你能澄清一下吗?那我该怎么办呢?
-
设置标题没有修复错误
-
"设置标题并没有修复错误" — 你是如何更改它们的?您是否为 redbubble 工作并可以访问他们的服务器?
-
所以我读到:“您无法在客户端代码中执行任何操作来启用 CORS 访问其他人的服务器。”我想弄清楚我现在应该怎么做?
标签: javascript node.js express webpack cors