最近自己写node后台的时候遇见一个问题,在egg框架中,跨域参数设置成
config.cors = {
origin: 'http://localhost:3000',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
};
无法进行session传递,登录接口获取session后并没存储起来
于是乎发现需要允许cookie跨域
config.cors = {
origin: 'http://localhost:3000',
credentials: true, // 支持cookie跨域
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
};
在前端请求中新增
axios({
method:'post',
url: checkLogin,
data:dataProps,
withCredentials: true // 增加cookie跨域
}).then(
res=>{
setIsLoading(false)
if(res.data.data=='登录成功'){
localStorage.setItem('openId',res.data.openId)
props.history.push('/index')
}else{
message.error('用户名密码错误')
}
}
)
经过这一系列操作后,发现,cookie还是没有正常存储,以为是配置有问题,开始从各个配置中开始寻找错误项,经过多种尝试无果,最后突然想到线上环境的页面经过ngnix反向代理后,接口才能正常存储cookie,于是我把我的本地路径改成了 http://127.0.0.1:3000/login
config.cors = {
origin: 'http://127.0.0.1:3000',
credentials: true, // 支持cookie跨域
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS'
};
意外的发现cookie可以正常的存储了,没想到最后的问题出在这里,如果大家在本地开发同意遇见了这样一个问题,大家可以尝试下这个方法。