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. javascript - vuejs 如何给option 添加点击事件2. html5 - vue项目中vuex存储问题3. mysql - spring data jpa 方法sql复杂查询?4. 微信订阅号如何用渠道二维码统计地推效果?5. 想练支付宝对接和微信支付对接开发(Java),好像个人不可以,怎么弄个企业的呢?6. javascript - QQ第三方登录的问题7. 并发 - python多进程+协程的正确姿势?8. python sqlalchemy create_engine问题9. 网页爬虫 - python爬虫翻页问题,请问各位大神我这段代码怎样翻页,还有价格要登陆后才能看到,应该怎么解决10. mysql - PHP 批量插入的时候 判断数据表里面是否重复怎么优化
