axios 跨域请求允许带cookie,则服务器Access-Control-Allow-Origin应设置为具体域名,

时间:2021-05-24 18:49:09

1、通过允许跨域访问实现了跨域请求,但为了使每个请求带上session信息,我设置了withCredentials ,即:
  axios.defaults.withCredentials = true
  然后跨域请求时会出现如下问题:
  Response to preflight request doesn‘t pass access control check: 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‘. Origin ‘http://localhost:8080‘ is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
  解决方案
    Access-Control-Allow-Origin 字段必须指定域名,不能为*
    Access-Control-Allow-Credentials为true

2.CORS
  同域安全策略CORS(Cross-Origin Resource Sharing)
  它要求请求的服务器在响应的报头(Response Header)添加 Access-Control-Allow-Origin标签,从而允许此标签所对应域访问此服务器的资源,调用此服务器的接口。
  缺陷:

    默认情况下,跨源请求不提供凭据(cookie、HTTP认证及客户端SSL证明等),通过将withCredentials属性设置为true,可以指定某个请求应该发送凭据。如果服务器接收带凭据的请求,会用下面的HTTP头部来响应:

1 Access-Control-Allow-Credentials: true


  如果发送的是带凭据的请求,但服务器的相应中没有包含这个头部,那么浏览器就不会把相应交给JavaScript,请求就无法得到结果的数据(浏览器得到了,但是我们请求的方法得不到,因为被浏览器拦截了),因此在需要传Cookie等时,服务端的Access-Control-    Allow-Origin必须配置具体的具体的域名。并且还需要设置其他的请求头:

1
2
3
4
header(‘Access-Control-Allow-Origin:http://www.xxx.com‘);
header(‘Access-Control-Allow-Credentials: true‘);   //是否支持cookie跨域
header(‘Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS‘);
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");