前端跨域请求,默认是不提供凭据(cookie、HTTP认证及客户端SSL证明等),所以跨域时候要携带cookie,要设置withCredentials
- 前端跨域携带cookie设置
axios({
url:'http://localhost:8888/api/search',
method:'get',
params: {
_t:+new Date()
},
withCredentials:true,
}).then(res => {
console.log(res.data);
console.log(document.cookie);
})
通过cors设置跨域携带cookie还要后端支持才可以
- 后端支持跨域携带cookie
app.all('*', function (req, res, next) { //支持跨域
// 允许请求的跨域来源,这里不能设置"Access-Control-Allow-Origin", " * ",
// 不然即使前端设置withCredentials:true后,cookie仍然带不过来
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
// 允许跨域携带cookie设置,
// 如果不设置为true, 前端请求携带了cookie,浏览器也会有结果,但是浏览器会阻止,所以请求的代码得不到cookie
res.header("Access-Control-Allow-Credentials",true);
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
if (req.method == "OPTIONS") {
res.send(200);
/*让options请求快速返回*/
} else {
next();
}
});
app.get('/api/search',function(req,res){
console.log(req.headers.cookie);
res.cookie('resc', '设置到cookie里的值', { expires: new Date(Date.now() + 900000) });
res.json({
errno:0,
data:'测试数据d'
})
res.end('cookies set ok')
})
- 前端设置,后端不设置 withCredentials请求仍然会失败
后端:
res.header("Access-Control-Allow-Credentials",false);
前端:
axios({
url:'http://localhost:8888/api/search',
method:'get',
params: {
_t:+new Date()
},
withCredentials:true,
}).then(res => {
// 进不来
}).cathc(e =>
// 进到这里来
console.log(e)
)