设置Cookie的浏览器上通过CORS Ajax请求(Set-Cookie on Browser w

2019-07-18 00:30发布

试图实现一个Ajax登陆/注册过程中(无刷新的网站身份验证)。 使用Cookie的保存状态。 我想我现在有这个权利,但由于某种原因,浏览器不设置cookies它得到他们从服务器返回后。 任何人都可以帮忙吗? 下面是请求和响应头:

Request URL:http://api.site.dev/v1/login
Request Method:POST
Status Code:200 OK

请求头

Accept:application/json, text/plain, */*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:57
Content-Type:application/json;charset=UTF-8
Host:api.site.dev
Origin:http://site.dev
Referer:http://site.dev/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11
withCredentials:true
X-Requested-With:XMLHttpRequest
Request Payload
{"email":"calvinfroedge@gmail.com","password":"foobar"}

响应头

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With, Content-Type, withCredentials
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:http://site.dev
Connection:Keep-Alive
Content-Length:19
Content-Type:application/json
Date:Tue, 08 Jan 2013 18:23:14 GMT
Keep-Alive:timeout=5, max=99
Server:Apache/2.2.22 (Unix) DAV/2 PHP/5.4.7 mod_ssl/2.2.22 OpenSSL/0.9.8r
Set-Cookie:site=%2B1THQQ%2BbZkEwTYFvXFVV5fxi00l2K%2B6fvt9SuHACTNsEwUGzDSUckt38ZeDsNbZSsqzHmPMWRLc84eDLZzh8%2Fw%3D%3D; expires=Thu, 10-Jan-2013 18:23:14 GMT; path=/; domain=.site.dev; httponly
X-Powered-By:PHP/5.4.7

我也看到在Chrome网络工具的饼干,因为从服务器返回:

响应cookie

Name: site
Value: %2B1THQQ%2BbZkEwTYFvXFVV5fxi00l2K%2B6fvt9SuHACTNsEwUGzDSUckt38ZeDsNbZSsqzHmPMWRLc84eDLZzh8%2Fw%3D%3D
Domain: .site.dev
Path: /
Expires: Session
Size: 196
Http: ✓

Answer 1:

您的AJAX请求必须以“withCredentials”设置为true进行(XMLHttpRequest2中唯一可用的和提取):

    var req = new XMLHttpRequest();
    req.open('GET', 'https://api.bobank.com/accounts', true); // force XMLHttpRequest2
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.setRequestHeader('Accept', 'application/json');
    req.withCredentials = true; // pass along cookies
    req.onload = function()  {
        // store token and redirect
        let json;
        try {
            json = JSON.parse(req.responseText);
        } catch (error) {
            return reject(error);
        }
        resolve(json);
    };
    req.onerror = reject;

如果您想对CORS,API安全,和饼干详细的解释,答案不适合在StackOverflow的评论。 看看这篇文章中,我关于这个问题写道: http://www.redotheweb.com/2015/11/09/api-security.html



Answer 2:

我有一个类似的问题,它原来的浏览器设置被阻断第三方Cookie(Chrome浏览器>设置>高级设置>隐私设置>内容设置>阻止第三方Cookie和网站数据)。 解锁问题解决了!



文章来源: Set-Cookie on Browser with Ajax Request via CORS