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

前端之家收集整理的这篇文章主要介绍了通过CORS通过Ajax请求在浏览器上设置Cookie前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试实现一个ajax登录/注册过程(不具有身份验证的刷新站点)。使用cookies来保存状态。我以为我现在有这个权利,但是由于某种原因,浏览器在从服务器恢复之后不设置cookie。任何人可以帮助?以下是请求和响应标头:
  1. Request URL:http://api.site.dev/v1/login
  2. Request Method:POST
  3. Status Code:200 OK

请求标头

  1. Accept:application/json,text/plain,*/*
  2. Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
  3. Accept-Encoding:gzip,deflate,sdch
  4. Accept-Language:en-US,en;q=0.8
  5. Connection:keep-alive
  6. Content-Length:57
  7. Content-Type:application/json;charset=UTF-8
  8. Host:api.site.dev
  9. Origin:http://site.dev
  10. Referer:http://site.dev/
  11. 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
  12. withCredentials:true
  13. X-Requested-With:XMLHttpRequest
  14. Request Payload
  15. {"email":"calvinfroedge@gmail.com","password":"foobar"}

回应标题

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

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

回应曲奇

  1. Name: site
  2. Value: %2B1THQQ%2BbZkEwTYFvXFVV5fxi00l2K%2B6fvt9SuHACTNsEwUGzDSUckt38ZeDsNbZSsqzHmPMWRLc84eDLZzh8%2Fw%3D%3D
  3. Domain: .site.dev
  4. Path: /
  5. Expires: Session
  6. Size: 196
  7. Http:
您的AJAX请求必须使用“withCredentials”设置设置为true(仅在XmlHttpRequest2和fetch中可用):
  1. var req = new XMLHttpRequest();
  2. req.open('GET','https://api.bobank.com/accounts',true); // force XMLHttpRequest2
  3. req.setRequestHeader('Content-Type','application/json; charset=utf-8');
  4. req.setRequestHeader('Accept','application/json');
  5. req.withCredentials = true; // pass along cookies
  6. req.onload = function() {
  7. // store token and redirect
  8. let json;
  9. try {
  10. json = JSON.parse(req.responseText);
  11. } catch (error) {
  12. return reject(error);
  13. }
  14. resolve(json);
  15. };
  16. req.onerror = reject;

如果您想要对CORS,API安全性和Cookie的详细说明,答案不适用于StackOverflow注释。看看这篇文章我写的主题http://www.redotheweb.com/2015/11/09/api-security.html

猜你在找的Ajax相关文章