您的位置:首页技术文章
文章详情页

node.js - koa 无法将cookie写入到客户端

【字号: 日期:2024-07-30 14:25:05浏览:90作者:猪猪

问题描述

登录接口在 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-cookiesnode.js - koa 无法将cookie写入到客户端

但是在浏览器的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();});

需要怎么调整?

相关文章: