注意:
新版Chrome浏览器导致 cookie 跨域失败,详见:cookie跨域失败-新版chrome浏览器SameSite属性
说明
关键代码:
axios.defaults.withCredentials = true;//带cookie
默认情况下,跨源请求 不提供凭据(cookie、HTTP认证及客户端SSL证明等)。
通过将 withCredentials 属性设置为 true,可以指定某个请求应该发送凭据。
取值说明:
- true:在跨域请求时,会携带用户凭证
- false:默认值。在跨域请求时,不会携带用户凭证;返回的 response 里也会忽略 cookie
axios 代码
非简单请求
axios 发送post请求,默认是 application/json ,所以是 非简单请求
axios.defaults.withCredentials = true;//带cookie
axios.post('http://localhost:8080/login',
{
"username":this.loginForm.username,
"password":this.loginForm.password
}
)
.then((res) => {
console.log(res);
this.loading = false
})
.catch(function (error) {// 请求失败处理
console.log(error);
});
简单请求
<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>
后端设置
filter 过滤器实现
详见:过滤器filter实现跨域,简单请求、非简单请求携带cookie