我已阅读建议here。我正在向我的服务发出XHR请求以获取cookie。我尝试确保Cookie中缺少域(不仅仅是一个空字符串)-
Set-Cookie: file-auth=MTU0ODIzODU1M3xEdi1CQkFFQ180SUFBUXdCREFBQUh2LUNBQUVGZG1Gc2RXVVRaRzkzYm14dllXUXRZWFYwYUc5eWFYcGxaQT09fPzBg_EP9S6wn_7gAz0iUtS1cOOaeo78VAMdD5xxhunF; Path=/; Expires=Thu, 24 Jan 2019 10:15:53 GMT
我尝试调整主机文件,以便向app.localhost.com:12350
发出请求,然后在Set-Cookie
标头中指定域-
Set-Cookie: file-auth=MTU0ODIzODg4NnxEdi1CQkFFQ180SUFBUXdCREFBQUh2LUNBQUVGZG1Gc2RXVVRaRzkzYm14dllXUXRZWFYwYUc5eWFYcGxaQT09fCdT3LhVhHIA6mPq_65ndnP1XFD2IEzLpxCmiaosHZA5; Path=/; Domain=app.localhost.com; Expires=Thu, 24 Jan 2019 10:21:26 GMT
我最初的XHR(GET)请求是向http://app.localhost.com:12350/test/file_service/setcookie
具有以下标题
GET /test/file_service/setcookie HTTP/1.1
Host: app.localhost.com:12350
Connection: keep-alive
Accept: application/json
Origin: http://app.localhost.com
Authorization: <MY-JWT>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Referer: http://app.localhost.com/tutorials
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
然后响应返回-
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://app.localhost.com
Access-Control-Expose-Headers: Content-Length
Content-Encoding: gzip
Set-Cookie: file-auth=MTU0ODIzODg4NnxEdi1CQkFFQ180SUFBUXdCREFBQUh2LUNBQUVGZG1Gc2RXVVRaRzkzYm14dllXUXRZWFYwYUc5eWFYcGxaQT09fCdT3LhVhHIA6mPq_65ndnP1XFD2IEzLpxCmiaosHZA5; Path=/; Domain=app.localhost.com; Expires=Thu, 24 Jan 2019 10:21:26 GMT
Vary: Accept-Encoding
Vary: Origin
Date: Wed, 23 Jan 2019 10:21:26 GMT
Content-Length: 23
Content-Type: application/x-gzip
但是,当向http://app.localhost.com:12350/test/file_service/file?
发出新的GET请求(不是XHR-我只是单击浏览器中的链接)时,不会发送cookie。在chrome调试器的cookie标签上,没有为域设置
我如何进行这项工作?
答案 0 :(得分:0)
XMLHttpRequest具有属性withCredentials
,该属性默认为false
。此属性定义是否将Set-Cookie
头用于跨源请求。
如果您将页面托管在http://app.localhost.com
上,但是调用http://app.localhost.com:12350
来获取cookie,那么如果Set-Cookie
属性未设置为{是的。
设置withCredentials
取决于您如何发出请求。在较旧的浏览器中-
withCredentials
但是更现代的解决方案是-
var client = new XMLHttpRequest()
client.open("GET", "./")
client.withCredentials = true
请参见here