注意:
新版Chrome浏览器导致 cookie 跨域失败,详见:cookie跨域失败-新版chrome浏览器SameSite属性
说明
关键代码:
axios.defaults.withCredentials = true;//带cookie
默认情况下,跨源请求 不提供凭据(cookie、HTTP认证及客户端SSL证明等)。
通过将 withCredentials
属性设置为 true
,可以指定某个请求应该发送凭据。
取值说明:
- true:在跨域请求时,会携带用户凭证
- false:默认值。在跨域请求时,不会携带用户凭证;返回的 response 里也会忽略 cookie
后端设置
当配置了 withCredentials = true
时,必须在后端增加 response
头信息 Access-Control-Allow-Origin
,且必须指定域名,而不能指定为 *
代码
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.defaults.withCredentials = true;//带cookie
axios.defaults.baseURL = 'http://localhost';
axios.get('/hello.json').then(function(res){
console.log(res);
console.log(res.data);
})
</script>