axios 跨域请求允许带cookie,则服务器Access-Control-Allow-Origin应设置为具体域名,否则请求无法获得返回数据

╄→гoц情女王★ 提交于 2019-12-04 15:33:13

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头部来响应:
    Access-Control-Allow-Credentials: true

  如果发送的是带凭据的请求,但服务器的相应中没有包含这个头部,那么浏览器就不会把相应交给JavaScript,请求就无法得到结果的数据(浏览器得到了,但是我们请求的方法得不到,因为被浏览器拦截了),因此在需要传Cookie等时,服务端的Access-Control-    Allow-Origin必须配置具体的具体的域名。并且还需要设置其他的请求头:
       Access-Control-Allow-Origin;           //request.getHeader("Origin") || www.xxx.com
       Access-Control-Allow-Methods;       //POST, GET, OPTIONS, DELETE
       Access-Control-Allow-Credentials;  //是否支持cookie跨域
       Access-Control-Allow-Headers;    //x-requested-with,content-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!