【问题标题】:Express enabling CORs headers still cause errorsExpress 启用 COR 标头仍然会导致错误
【发布时间】: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


【解决方案1】:

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

localhost:3333/us

这是您可以在浏览器中输入的内容,浏览器会自动为其添加协议(浏览器会做各种事情来尝试将您在 URl 栏中输入的内容变成合法的 URL,但该逻辑确实如此通过 Javascript 和 Ajax 发出的请求不会发生)。相反,将 URL 更改为:

http://localhost:3333/us

【讨论】:

    【解决方案2】:

    我建议仅 npm 安装“cors”作为依赖项。完成后,只需在要允许 CORS 的所有路由之前 require 和 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      相关资源
      最近更新 更多