node.js - koa 无法将cookie写入到客户端
本文介绍了node.js - koa 无法将cookie写入到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
登录接口在 api.site.com 下,登录之后会把用户的access_token 以cookie 的方式往 site.com 这个域名下写,但是刷新页面之后在请求头里面看不到cookie,this.cookies.get()也是undefined,说明没有写成功。
使用的是本地开发环境,api.site.com 和 www.site.com 实际上都是 localhost(127.0.0.1),改的host实现的
代码如下:
if(validateEmail && validateUsername) {
let [User] = yield this.db.query(sql, user);
let id = User.id
const token = yield user.generateAccessToken(id);
this.cookies.set('access_token', token, {
domain: '.site.com'
})
this.body = User;
}
求大神支招
更新
整了个 nginx 代理,问题依然存在
可以在response header 里面看到服务器端有写入的 set-cookies
但是在浏览器的cookies 里面看不到,页面请求也没有携带这个cookie
解决方案
这两天搜遍了google,so,尼玛终于找到问题了,觉得非常有必要自己记录一下。
全都是因为这个鬼东西 Request.credentials
The credentials read-only property of the Request interface indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests. This is similar to XHR’s withCredentials flag, but with three available values (instead of two):
omit: Never send cookies.
same-origin: Only send cookies if the URL is on the same origin as the calling script.
include: Always send cookies, even for cross-origin calls.
当我们在发送跨域请求时,request 的 credentials属性表示是否允许其他域发送cookie,
该属性有3个值:
omit: 默认属性,不允许其他域发送cookie
same-origin: 只允许同域发送cookie
include: 总是允许发送cookie
所以必须在发送post请求时加上 credentials: include,
使用jq的话就是
$.ajax({
url: 'http://api.site.com/users',
type: 'POST',
data: postData,
xhrFields: {
withCredentials: true
},
success: function (data) {
console.log(data)
}
})
同时在服务端必须加上:
‘Access-Control-Allow-Credentials’:true
这个问题困扰了好多天,还是读书太少。。。
这篇关于node.js - koa 无法将cookie写入到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文