网上的答案,有道理,但不太对,

response.headers['Access-Control-Allow-Credentials'] = 'true'
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Requested-With'

报错问题


The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is'include'.

原因:

  1. 后台不能使用通配符 ‘*’,否则前端报错;

  2. 请求的 origin 和后台设置的 origin 不一致。

解决方案: 

前端代码不用动。

后台 为 ‘Access-Control-Allow-Origin’ 设置动态的 origin。

Java: 

response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
 

Node 的 httpserver:

response.headers['Access-Control-Allow-Origin'] = request.environ['HTTP_ORIGIN']