使用 Eve 和 AngularJS 的 CORS 问题

Trouble with CORS using Eve and AngularJS

我正在 Eve 和 AngularJS 中使用 API 开发应用程序。 为了避免 CORS 问题,我制作了一个简单的 NodeJS 服务器来为我的静态文件提供服务。 但是,即使在我的 Python Eve API 通过编写 'X_DOMAINS': '*' 允许所有域之后(我使用 Curl 进行了测试并且它有效),当我想调用API 使用 $http.

这是我在 chrome 中遇到的错误:

XMLHttpRequest cannot load http://localhost:5000/regions. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

我什至在我的 Node 应用程序中写了这个,尽管我认为它没有用:

app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
  res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
  next();
});

到目前为止没有任何效果,在此先感谢您的帮助!

在您的回复中添加此内容 headers:

res.header("Access-Control-Allow-Origin", "http://localhost:8080");

删除以下内容:

http://localhost:8080

或者您可以尝试获取请求来源并将其添加到响应中。像这样:

var hostName = req.get('host');
res.header("Access-Control-Allow-Origin", hostName);

在某些情况下它可能会起作用,特别是如果它是 GET 调用。但是如果是POST,一些浏览器会屏蔽它。

另一种选择是禁用浏览器上的网络安全(尽管这不是最好的做法。)您可以阅读 here 了解相关信息。

也浏览一下帖子 here ,这样您可以更好地了解问题。

在以下命令中: res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");

您设置允许 headers,也许您发送了其他 headers 例如"Authorization",在这种情况下,您必须将这些 headers 添加到上面的命令

运行 与 javascript 有一些类似的问题。我可以在前夕 运行 进行一些调整,但最终还是不够。 BadRequest 响应由 flask 引擎发送,而不是 eve,禁用任何 javascript 处理错误的尝试。似乎有一个很好的烧瓶扩展 CORS 很好地涵盖了它:

from flask.ext.cors import CORS
....
CORS(app)

这就是我最终需要的。