Access-Control-Allow-Origin:当凭据标志为真时不允许使用“*”,但没有 Access-Control-Allow-Credentials header

Access-Control-Allow-Origin: "*" not allowed when credentials flag is true, but there is no Access-Control-Allow-Credentials header

突然之间,似乎没有更改我的网络应用程序中的任何内容,我在 Chrome 中打开它时开始出现 CORS 错误。我尝试添加一个 Access-Control-Allow-Origin: * header。然后我得到这个错误:

XMLHttpRequest cannot load http://localhost:9091/sockjs-node/info?t= 1449187563637. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3010' is therefore not allowed access.

但是如下图所示,没有Access-Control-Allow-Credentials header.

卧槽? Chrome 错误?

我的页面在 http://localhost:3010 加载并且该服务器也使用 Access-Control-Allow-Origin: * 没有问题。两个端点都用有问题吗?

"credentials flag" 指的是请求的 XMLHttpRequest.withCredentials,而不是 Access-Control-Allow-Credentials header。 那是我困惑的根源。

如果请求的withCredentialstrueAccess-Control-Allow-Origin: *不能使用,即使没有Access-Control-Allow-Credentialsheader.

我使用这些步骤解决了同样的问题..

1) 禁用您的 chrome 扩展 "Allow-Control-Allow-Origin"

2) 将这些添加到您的服务中

var xhr = new(); xhr.withCredentials = 真;

请求 withCredentials:true,在配置有 Access-Control-Allow-Origin: * 的服务器上可以使用,但您需要在服务器上进行更多额外配置:

在服务器上使用 Access-Control-Allow-Origin=*,它将不允许在任何 xhr CORS 请求上访问任何资源(需要凭据)。

解决方法:

  1. 使服务器上的远程资源无需凭据即可访问 (并使用 xhr.withCredentials = false
  2. 创建重写规则 服务器,修改响应 header Access-Control-Allow-Origin=* 到请求的来源。你可以 在某些条件下也应用此重写,例如,如果 请求正在使用某个端口或来自白名单列表 域。

这里有一些 article that explains how to do this on a IIS server,但您可以在许多其他服务器上这样做:

PS:如果使用凭据,您还需要在服务器响应中包含以下 header:Access-Control-Allow-Credentials=true

PS2: "access-control-allow-origin" 参数只允许有 1 个值。例如,如果您尝试使用两个域:domain1.com domain2.com,它将不起作用。