【发布时间】:2017-02-20 12:36:51
【问题描述】:
使用http://enable-cors.org/ for express 提供的代码,我已添加到我的 index.js 文件中
/*these first five line direct from http://enable-cors.org/.com*/
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var PORT = 3333;
app.listen(PORT, function(){
console.log('listening on port', PORT);
})
request({url: 'http://bl.ocks.org/mbostock/raw/4090846/us.json', json: true}, function(err, data){
app.get('/us', function(req, res, next){
console.log(req) //prints correctly
res.json(data.body);
});
});
localhost:3333/us 正确显示 json,但从 localhost:3000(browsersync 服务的端口)发出请求失败并出现错误
d3.min.js:1XMLHttpRequest cannot load localhost:3333/us. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
这不再是在 express 上为 localhost 启用 CORS 的正确方法了吗?我还尝试将 app.use 方法 '*' 和 '/us' 作为其第一个参数传递,但没有运气。
【问题讨论】:
-
这是一个重要线索:“跨源请求仅支持协议方案”请包括您用于发送此 ajax 请求的代码,因为显然它不是 http 或 https,意思是可能与您的服务器无关。
-
@KevinB 你是对的。当我添加
http时,我收到了ERR_CONNECTION_REFUSED但我相信这是因为我打开了 CORs chrome 扩展。删除它已经消除了错误。谢谢。
标签: javascript node.js google-chrome express cors