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
问题解答
回答1:这两天搜遍了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: 默认属性,不允许其他域发送cookiesame-origin: 只允许同域发送cookieinclude: 总是允许发送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
这个问题困扰了好多天,还是读书太少。。。
回答2:用token
回答3:先用浏览器F12看一下cookies里面确定有了你放的token
回答4:朋友我跟你同样的问题,后台代码是
this.cookies.set(’c’, ’3’,{domain:’localhost’,httpOnly:true);
前台同样是在response Headers 里面能看到Set-Cookies
你是说后台
this.cookies.set(’c’, ’3’,{domain:’localhost’,httpOnly:true,’Access-Control-Allow-Credentials’:true})
这样子改吗?前端请求怎么办?我的前端请求是这个样子的:
$.post('http://localhost:8080/user/userlogin?username='+username+'&password='+password,function(data,status){ alert('Data: ' + data.toString()+ 'nStatus: ' + status); let userinfo = data[0]; $('#txtUsername').html(userinfo.username); $('#txtp').show();});
需要怎么调整?
相关文章:
1. 下一个页面的三角在上面一个页面会出现,在缩放的时候会遮住文字。2. android - mac平台运行快捷键咋按3. mysql优化 - mysql 多表联合查询,求一个效率最高的查询4. weex - Android 原生Vue.js 使用 justify-content: flex-end; 不起作用5. 数据库 - mysql中怎样修改带点的字段名的位置?6. python - Django ManyToManyField 字段数据在 admin后台 显示不正确,这是怎么回事?7. php由5.3升级到5.6后,登录网站,返回的是php代码,不是登录界面,各位大神有知道的吗?8. 为什么span的color非要内联样式才起作用?9. mysql 能不能创建一个 有列级函数 的联合视图?10. javascript - vue-cli热更新的问题【webpack配置】

网公网安备