node.js - 尽管未设置 Access-Control-Allow-Credentials,但我收到 CORS 错误

标签 node.js heroku http-post cors

我用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 网络选项卡中失败的请求和响应:

enter image description here

为什么它提示 credentials 标志?

最佳答案

我们终于解决了这个问题。以下是我们的发现以及引导我们找到解决方案的思路:

  • CORS 问题仅发生在 POST 过程中,而不是 GET 过程中。
  • 仅当我从 URL 以 file:// 开头的本地 HTML 发出请求时,才会发生 CORS 问题。当我从 http://localhost 请求时没有问题。
  • file:// 协议(protocol)发起 POST 请求时,来源为 null。事实证明,问题在于 null 未被通配符 * 覆盖。
  • Allow-Access-Control-Origin 设置为 null 还不够,因为显然来自 origin null 的请求包含凭据,因此我必须将 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/

相关文章:

javascript - Docker容器nodejs连接外部mysql失败

javascript - 等待一个在一系列 promise 中返回真值的 promise

ruby - Sidekiq 正在提升我在 New Relic 中的性能监控

javascript - 加载bundle.js(Http/Https)时发生混合内容错误

python - 在 connexion/flask 应用程序中,如何伪造端点正文中带有参数的发布请求?

excel - 如何使用 Excel 公式(无 VBA)在 HTTP POST 响应中检索一段数据?

javascript - node.js request.js 不并行触发请求

javascript - 强大/NodeJS HTTP服务器JPG保存

git - 在使用 Git 或 SSH 复制/远程登录等时,我们应该重复使用相同的 SSH key 还是每次都创建新 key ?

perl - 如何使用 LWP 发出 JSON POST 请求?