ajax中的withCredentials使用

2,600 阅读1分钟

XMLHttpRequest.withCredentials 有什么用?

跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等) 也可以简单的理解为,当前请求为跨域类型时是否在请求中协带cookie。

XMLHttpRequest.withCredentials 怎么用?

withCredentials属于XMLHttpRequest对象下的属性,可以对其进行查看或配置。

配置withCredentials:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', 'http://www.lovejavascript.com/learnLinkManager/getLearnLinkList', true);
xhr.onreadystatechange = function() {
  console.log('withCredentials=>', xhr.withCredentials);
};
xhr.send(null);

  需要注意是,当配置了xhr.withCredentials = true时,必须在后端增加 response 头信息Access-Control-Allow-Origin,且必须指定域名,而不能指定为*。

如果在同域下配置xhr.withCredentials,无论配置true还是false,效果都会相同,且会一直提供凭据信息(cookie、HTTP认证及客户端SSL证明等)

  Access-Control-Allow-Credentials 响应头表示是否可以将对请求的响应暴露给页面。返回true则可以,其他值均不可以。

Access-Control-Allow-Credentials 头 工作中与XMLHttpRequest.withCredentials 或Fetch API中的Request() 构造器中的credentials 选项结合使用。

Credentials必须在前后端都被配置(即the Access-Control-Allow-Credentials header 和 XHR 或Fetch request中都要配置)才能使带credentials的CORS请求成功。