登录接口在 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
PHP中文网2017-04-17 15:27:25
After searching Google for the past two days, I finally found the problem and felt it was necessary to record it myself.
It’s all because of this damn thing 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.
When we send a cross-domain request, the credentials attribute of the request indicates whether other domains are allowed to send cookies.
This attribute has 3 values:
omit: Default attribute, other domains are not allowed to send cookies
same-origin: Only allow sending cookies from the same domain
include: Always allow sending cookies
So you must add credentials: include when sending a post request,
If you use jq, it is
$.ajax({
url: 'http://api.site.com/users',
type: 'POST',
data: postData,
xhrFields: {
withCredentials: true
},
success: function (data) {
console.log(data)
}
})
At the same time, on the server side, you must add:
‘Access-Control-Allow-Credentials’:true
This problem has been bothering me for many days, and I still read too little. . .
PHPz2017-04-17 15:27:25
First use browser F12 to check the cookies to make sure there is the token you put in
伊谢尔伦2017-04-17 15:27:25
Friend, I have the same problem as you, the background code is
this.cookies.set('c', '3',{domain:'localhost',httpOnly:true);
Set-Cookies can also be seen in the response Headers at the front desk
You mean backstage
this.cookies.set('c', '3',{domain:'localhost',httpOnly:true,'Access-Control-Allow-Credentials':true})
Is this the way to change it?
What to do with front-end requests?
My front-end request looks like this:
$.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();
});
What adjustments need to be made?