本文介绍了设置Cookie的浏览器通过CORS Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 请求的URL:http://api.site.dev/v1/login
请求方法:POST
状态code:200 OK
 

请求头

 接受:应用/ JSON,纯文本/,* / *
接收字符集:ISO-8859-1,UTF-8,Q = 0.7,*; Q = 0.3
接受编码:gzip,紧缩,SDCH
接受语言:EN-US,EN; Q = 0.8
连接:保持活动
内容长度:57
内容类型:应用程序/ JSON;字符集= UTF-8
主持人:api.site.dev
原产地:HTTP://site.dev
引用站点:HTTP://site.dev/
用户代理:Mozilla的/ 5.0(Macintosh电脑;英特尔的Mac OS X 10_8_2)为AppleWebKit / 537.11(KHTML,像壁虎)的Chrome / Safari浏览器23.0.1271.101 / 537.11
withCredentials:真
的X请求 - 由于:XMLHtt prequest
请求负载
{电子邮件:calvinfroedge@gmail.com,密码:foobar如果}
 

响应头

 访问控制 - 允许-凭据:真
访问控制 - 允许 - 头:X-请求,通过,内容类型,withCredentials
访问控制 - 允许 - 方法:GET,POST,PUT,DELETE,OPTIONS
访问控制 - 允许 - 产地:HTTP://site.dev
连接:保持活动
内容长度:19
内容类型:应用程序/ JSON
日期:星期二,2013年1月8日18点23分14秒格林尼治标准​​时间
保持活动:超时= 5,最大值= 99
服务器: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;到期=周四,10-JAN-2013十八时23分14秒格林尼治标准​​时间;路径= /;域= .site.dev;仅Http
的X已启动方式:PHP / 5.4.7
 

我也看到在Chrome网络工具的cookie,从服务器返回的:

响应cookie

 名称:网站
值:%2B1THQQ%2BbZkEwTYFvXFVV5fxi00l2K%2B6fvt9SuHACTNsEwUGzDSUckt38ZeDsNbZSsqzHmPMWRLc84eDLZzh8%2Fw%3D%3D
域名:.site.dev
路径: /
过期:会话
尺寸:196
HTTP:✓
 

解决方案

您AJAX请求必须由具有withCredentials设置设置为true(只适用于XmlHtt prequest2和获取):

  VAR REQ =新XMLHtt prequest();
    req.open(GET,https://api.bobank.com/accounts,真正的); //力XMLHtt prequest2
    req.setRequestHeader(内容类型,应用/ JSON的;字符集= UTF-8);
    req.setRequestHeader(接受,应用/ JSON);
    req.withCredentials = TRUE; //沿饼干通
    req.onload =功能(){
        //存储令牌和重定向
        让JSON;
        尝试 {
            JSON = JSON.parse(req.responseText);
        }赶上(错误){
            回报拒绝(错误);
        }
        解析(JSON);
    };
    req.onerror =拒绝;
 

如果你想在CORS,API的安全性,和饼干的详细说明,答案不适合在一个计算器评论。看看这篇文章我写了关于这个问题的: HTTP://www.redotheweb .COM /十一分之二千〇十五/ 09 / API-security.html

Attempting to implement an ajax login / signup process (no refresh site with authentication). Using cookies for preserving state. I thought I'd have this right by now but for some reason browser doesn't set cookies after it gets them back from the server. Can anyone help? Here are the request and response headers:

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

I also see the cookie in chrome network tools, as returned from the server:

Response Cookies

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

Your AJAX request must be made with the "withCredentials" settings set to true (only available in XmlHttpRequest2 and 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;

If you want a detailed explanation on CORS, API security, and cookies, the answer doesn't fit in a StackOverflow comment. Check out this article I wrote on the subject: http://www.redotheweb.com/2015/11/09/api-security.html

这篇关于设置Cookie的浏览器通过CORS Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 12:10
查看更多