技术栈
- 后台
node + express + MongoDB - 前端
react
问题详情
- 做个人项目时,想通过cookie的方式做免登陆功能,后台设置了返回 cookie,并且响应头中也带了
Set-Cookie
,但是并无法设置到 Application
中。
if (md5(password) === result.password) {
res.cookie('userId', result._id, { maxAge: 1000*60*60*24})
const data = {_id: result._id, username, phone}
res.send({code: 0, data})
}
// 当时还踩了一个坑,就是设置了 httpOnly: true,这个时候js怎么也访问不到cookie的值,
// 后来查了一下,如果在cookie中设置了HttpOnly 属性,那么js就无法读取cookie信息,这种做法可以防止XSS攻击
// res.cookie('userId', result._id, { maxAge: 1000*60*60*24, httpOnly: true })
- 浏览器信息
解决方案
后台解决方案
- 由于前后台端口号不一致,违反了同源策略,所以出现了跨域,由此需要解决跨域问题,此时用的是服务端设置响应头的方式,设置
Access-Control-Allow-Credentials", true
,但是需要不要将origin 设置 为 '*'
,例如 Access-Control-Allow-Origin', '*'
的方式,这样的话两者会起冲突。解决方案是设置一个允许访问的白名单,判断请求的origin
源是否来自于白名单。// 白名单
let whiteList = ['http://localhost:3000']
// 解决跨域问题
app.use((req, res, next) => {
let origin = req.headers.origin
if (whiteList.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader("Content-Type", "application/json;charset=utf-8");
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Access-Token");
res.setHeader('Assess-Control-Allow-Methods', 'GET, POST')
res.setHeader("Access-Control-Allow-Credentials", true);
} else {
res.send('出现跨域问题')
}
next()
})
前端解决方案
小结
出现这个问题的主要原因其实还是没有理解cookie的使用的流程
cookie的使用流程
1. 服务器制作生成cookie
2. 服务器将cookie发送给客户端
3. 客服端保存cookie
4. 客户端再次访问服务器时,携带cookie
5. 服务器检查客服端发回的cookie
既然客服端访问服务器会携带cookie,那么axios请求时带cookie了嘛?
目前这种方法很多大厂已经不再使用,而是使用的token