node.js - koa 無(wú)法將cookie寫(xiě)入到客戶端
問(wèn)題描述
登錄接口在 api.site.com 下,登錄之后會(huì)把用戶的access_token 以cookie 的方式往 site.com 這個(gè)域名下寫(xiě),但是刷新頁(yè)面之后在請(qǐng)求頭里面看不到cookie,this.cookies.get()也是undefined,說(shuō)明沒(méi)有寫(xiě)成功。
使用的是本地開(kāi)發(fā)環(huán)境,api.site.com 和 www.site.com 實(shí)際上都是 localhost(127.0.0.1),改的host實(shí)現(xiàn)的
代碼如下:
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;}
求大神支招
更新
整了個(gè) nginx 代理,問(wèn)題依然存在
可以在response header 里面看到服務(wù)器端有寫(xiě)入的 set-cookies
但是在瀏覽器的cookies 里面看不到,頁(yè)面請(qǐng)求也沒(méi)有攜帶這個(gè)cookie
問(wèn)題解答
回答1:這兩天搜遍了google,so,尼瑪終于找到問(wèn)題了,覺(jué)得非常有必要自己記錄一下。全都是因?yàn)檫@個(gè)鬼東西 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.
當(dāng)我們?cè)诎l(fā)送跨域請(qǐng)求時(shí),request 的 credentials屬性表示是否允許其他域發(fā)送cookie,該屬性有3個(gè)值:omit: 默認(rèn)屬性,不允許其他域發(fā)送cookiesame-origin: 只允許同域發(fā)送cookieinclude: 總是允許發(fā)送cookie
所以必須在發(fā)送post請(qǐng)求時(shí)加上 credentials: include,使用jq的話就是
$.ajax({url: ’http://api.site.com/users’,type: ’POST’,data: postData,xhrFields: { withCredentials: true},success: function (data) { console.log(data)} })
同時(shí)在服務(wù)端必須加上:
‘Access-Control-Allow-Credentials’:true
這個(gè)問(wèn)題困擾了好多天,還是讀書(shū)太少。。。
回答2:用token
回答3:先用瀏覽器F12看一下cookies里面確定有了你放的token
回答4:朋友我跟你同樣的問(wèn)題,后臺(tái)代碼是
this.cookies.set(’c’, ’3’,{domain:’localhost’,httpOnly:true);
前臺(tái)同樣是在response Headers 里面能看到Set-Cookies
你是說(shuō)后臺(tái)
this.cookies.set(’c’, ’3’,{domain:’localhost’,httpOnly:true,’Access-Control-Allow-Credentials’:true})
這樣子改嗎?前端請(qǐng)求怎么辦?我的前端請(qǐng)求是這個(gè)樣子的:
$.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();});
需要怎么調(diào)整?
相關(guān)文章:
1. angular.js - webpack build后的angularjs路由跳轉(zhuǎn)問(wèn)題2. java - web項(xiàng)目中,用戶登陸信息存儲(chǔ)在session中好 還是cookie中好,取決于什么?3. java - Activity中的成員變量被賦值之后,Activity被回收的時(shí)候內(nèi)存才會(huì)被釋放嗎4. Discuz! Q 有人用過(guò)嗎?5. 數(shù)組按鍵值封裝!6. 我寫(xiě)的哪里有錯(cuò)?請(qǐng)大神幫忙查看一下。7. 請(qǐng)求一個(gè)數(shù)據(jù)返回內(nèi)容為空或者錯(cuò)誤如何再次請(qǐng)求幾次8. 使用list和each配合,的作業(yè),輸出一行后,如何換行9. php由5.3升級(jí)到5.6后,登錄網(wǎng)站,返回的是php代碼,不是登錄界面,各位大神有知道的嗎?10. 為什么bindClass訪問(wèn)不了的?
