即使我收到set-cookie响应标头,cookie也不会写入

时间:2017-04-05 07:47:33

标签: django angular cookies

浏览器忽略了响应cookie(csrftoken + seesionid)。 document.cookie()返回空字符串,Chrome开发者工具显示this site has no cookies

如何解决这个问题?

FRONT: Angular 2(localhost:4200)

返回: Django / DRF(localhost:8000)

登录路线: [post] / login

回复标题:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:4200
Allow:POST, OPTIONS
Date:Wed, 05 Apr 2017 07:38:24 GMT
Server:WSGIServer/0.2 CPython/3.5.2
Set-Cookie:sessionid=d5v1mri12bniyvyqqt55ar8mfl9mr2jk; expires=Wed, 19-Apr-2017 07:38:24 GMT; HttpOnly; Max-Age=1209600; Path=/
Set-Cookie:csrftoken=5PcTF8aQ1O79gdrylZcGchnmKyRy6zwS3kL2jR5dY2CMdjPfEYyhkoJjOzsDZuvj; expires=Wed, 04-Apr-2018 07:38:24 GMT; Max-Age=31449600; Path=/
Vary:Accept, Cookie, Origin
X-Frame-Options:SAMEORIGIN

请求标题:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Content-Length:51
content-type:application/json
Cookie:sessionid=d5v1mri12bniyvyqqt55ar8mfl9mr2jk; csrftoken=sml3uocRIeiB3KfHSnNkJXBJn3QAFN3p7lLtdvhrALgUwoVnfNjGM5PIy2L3UHls
Host:127.0.0.1:8000
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/56.0.2924.76 Chrome/56.0.2924.76 Safari/537.36

2 个答案:

答案 0 :(得分:2)

Cookie不会在主机的不同端口之间共享(在您的情况下为localhost)。浏览器显示localhost:4200中的内容,但cookie设置为localhost:8000。正确设置和使用它们,如第二个标题为" Request header"的列表中所示。因此,要在浏览器中查看它们,您必须从localhost:8000打开一个URL。即使这样,sessionid也不会列在document.cookie()中,因为它被标记为" HttpOnly" (这意味着JavaScript不可用)。

答案 1 :(得分:0)

如果您使用的是角度cli,则可以设置代理。

ng serve --proxy-config proxy.conf.json

proxy.conf.json的示例 { "/api": { "target": "http://localhost:3000", "secure": false } }

或本地开发使用 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi