首页 文章

通过CORS使用Ajax请求在浏览器上设置Cookie

提问于
浏览
39

尝试实现ajax登录/注册过程(没有带身份验证的刷新站点) . 使用cookie来保存状态 . 我以为我现在已经有了这个权利,但由于某些原因浏览器在从服务器返回后没有设置cookie . 有人可以帮忙吗?以下是请求和响应标头:

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

Request Headers

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"}

Response Headers

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:

Response Cookies

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

2 回答

  • 26

    您的AJAX请求必须在“withCredentials”设置为true的情况下进行(仅在XmlHttpRequest2和fetch中可用):

    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安全性和cookie的详细说明,则答案不适合StackOverflow注释 . 看看我写的关于这个主题的文章:http://www.redotheweb.com/2015/11/09/api-security.html

  • 6

    我遇到了类似的问题,结果发现浏览器设置阻止了第三方Cookie(Chrome>设置>高级设置>隐私>内容设置>阻止第三方Cookie和网站数据) . 解锁解决了这个问题!

相关问题