【问题标题】:Node can't read Access-control-allow-origin header节点无法读取 Access-control-allow-origin 标头
【发布时间】:2015-12-03 04:01:48
【问题描述】:

好吧,这很奇怪,我有以下 server.js 文件,其中包含以下代码:

    app.all('/*', function (req, res, next) {
    // CORS headers
    res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    // Set custom headers for CORS
    res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
    if (res.method === 'OPTIONS') {
        res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
        // Set custom headers for CORS
        res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
    }
    next();
});

现在我的系统调用的域是api.example.com

我从另一个名为 angular.example.com 的网站调用它

当我这样做时,我在控制台中收到以下错误消息:

XMLHttpRequest cannot load http://api.example.com/api/componentsByModule/125 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://angular.example.com' is therefore not allowed access. The response had HTTP status code 503.

但正如您从我上面的代码中看到的那样,它应该为所有请求设置标头

所以我的问题是我做错了什么?

【问题讨论】:

  • 这两个网站您都在使用自己的网站吗? Access-Allow-Control-Origin 设置由站点所有者在其服务器上管理。我还没有设计出一种方法来允许它在我的应用程序中从我的域访问另一个域。有趣的是,cURL 调用工作正常,而 HURL.it 非常适合查看对给定 URL 的调用的响应标头。但是,如果您不拥有您尝试访问的域,或者无法控制服务器的配置文件,则无法在此处注入允许的跨站点脚本 (XSS/CORS) 访问权限:(hurl.it)
  • @MikeHorstmann 我的两个网站都由我管理,但是我有多个子域指向相同的 ip
  • app.use 是在 express 中添加中间件的更惯用的方式,而不是更冗长的 app.all('/*'
  • 如果您在其中console.log 或调试到断点,该代码是否实际执行您期望的请求?您是否使用curlhttpie 等更好的工具查看原始响应以验证标头是否存在?

标签: node.js express header http-status-code-503


【解决方案1】:

在 express 中添加中间件的顺序至关重要。您需要确保您的 sn-p 发生在所有其他应用程序路由之前。它应该在您最初创建 app 实例后不久。

【讨论】:

  • 这是我实例化我的应用程序后的第一件事
猜你喜欢
  • 2016-01-11
  • 2018-01-24
  • 2019-02-07
  • 2014-04-25
  • 1970-01-01
  • 2018-10-28
  • 2016-01-21
  • 2018-07-18
  • 2019-03-18
相关资源
最近更新 更多