【发布时间】: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或调试到断点,该代码是否实际执行您期望的请求?您是否使用curl或httpie等更好的工具查看原始响应以验证标头是否存在?
标签: node.js express header http-status-code-503