繁体   English   中英

快速启用CORs标头仍然会导致错误

[英]Express enabling CORs headers still cause errors

使用http://enable-cors.org/提供的代码进行表达,我已经添加到我的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上为本地主机启用CORS的正确方法吗? 我也尝试过将app.use方法'*''/us'作为第一个参数,但是没有运气。

进行Ajax调用时,您需要一个包含协议的标准URL。 这不是合法的网址:

localhost:3333/us

您可以在浏览器中键入此内容,浏览器将自动向其中添加一个协议(浏览器会进行各种操作,以尝试将您在URl栏中键入的内容转换为合法的URL,但这种逻辑不会发生通过Javascript和Ajax发出的请求)。 而是将URL更改为:

http://localhost:3333/us

我建议仅npm安装“ cors”作为依赖项。 完成后,只需在要允许CORS的所有路线之前使用app.use。

 // Dependancies var cors = require('cors'); // Init express app var app = express(); app.use(cors()); // Routes now allow cors app.get('/api/endpoint', controllers.endpoint); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM