Axios不能自动发送Cookie,需要配置Axios请求头,将Cookie添加到请求中。使用如下代码示例可以解决此问题:
import axios from 'axios';
axios.defaults.withCredentials = true; // 设置跨域请求中允许携带cookie
axios.get('/api/user', {
headers: {
'X-Requested-With': 'XMLHttpRequest' // 自定义请求头
}
}).then(res => {
console.log(res.data);
}).catch(err => {
console.error(err);
});
在代码示例中,通过将axios.defaults.withCredentials
设置为true
,允许向跨域请求中添加Cookie。请求头中'X-Requested-With': 'XMLHttpRequest'
是自定义请求头,也可以根据具体需求设置对应的请求头。