最近做vue+node的demo中,遇到了关于在后端设置跨域访问后session保存不了值的问题,第一次保存登录信息req.session.login = user,当登录成功后去取出session中的值,发现req.session.login = undefined,查阅资料后发现了问题并得以解决。
在设置跨域访问的代码如下:
app.
use(
function(
req,
res,
next) {
//设置跨域访问
res.
header(
'Access-Control-Allow-Origin',
'*');
res.
header(
'Access-Control-Allow-Headers',
'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.
header(
'Access-Control-Allow-Methods',
'PUT, POST, GET, DELETE, OPTIONS');
if (
req.
method ==
'OPTIONS') {
res.
send(
200);
/*让options请求快速返回*/
}
else {
next();
}
})
然而CORS请求默认不发送cookie和HTTP认证信息,如果要把cookie发送到服务器,一方面要服务器同意,指定:
res.
header(
'Access-Control-Allow-Origin',
'http://localhost:8080');
res.
header(
'Access-Control-Allow-Credentials',
true);
而且Access-Control-Allow-Origin就不能设为星号,必须指定明确的,与请求网页一致的域名,关于跨域资源共享CORS的知识参考于阮一峰的博客文章http://www.ruanyifeng.com/blog/2016/04/cors.html
另一方面需要在前端指定:
axios.defaults.withCredentials = true;