我用node.js和express编写了一个服务器应用程序。该应用程序使用 cors带有来源 "*"
的 POST 请求的 Node 包,因为我需要能够从移动应用程序发布。
以下是如何在应用程序中启用 CORS:
var cors = require('cors');
var app = express();
app.configure(function() {
app.use(cors());
});
当我尝试从浏览器发送请求时,收到此错误:
XMLHttpRequest cannot load url. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access.
但是,我在响应中没有看到任何 Access-Control-Allow-Credentials header 。以下是 Chrome 网络选项卡中失败的请求和响应:
为什么它提示 credentials
标志?
最佳答案
我们终于解决了这个问题。以下是我们的发现以及引导我们找到解决方案的思路:
- CORS 问题仅发生在 POST 过程中,而不是 GET 过程中。
- 仅当我从 URL 以
file://
开头的本地 HTML 发出请求时,才会发生 CORS 问题。当我从http://localhost
请求时没有问题。 - 从
file://
协议(protocol)发起 POST 请求时,来源为null
。事实证明,问题在于null
未被通配符*
覆盖。 - 将
Allow-Access-Control-Origin
设置为null
还不够,因为显然来自 originnull
的请求包含凭据,因此我必须将Allow-Access-Control-Credentials
设置为true
。
这是我更新的服务器代码,它接受来自任何来源的 POST 请求,包括与 file://
配合使用的移动应用程序中的 Web View :
var cors = require('cors');
var app = express();
app.configure(function() {
app.use(cors({ origin: 'null', credentials: true }));
});
关于node.js - 尽管未设置 Access-Control-Allow-Credentials,但我收到 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34194990/