XMLHttpRequest.withCredentials 有什么用?

跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等)

也可以简单的理解为,当前请求为跨域类型时是否在请求中协带cookie。

XMLHttpRequest.withCredentials 怎么用?

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

查看withCredentials:

var xhr = new XMLHttpRequest();

xhr.open('GET', 'http://www.lovejavascript.com/learnLinkManager/getLearnLinkList', true);

xhr.onreadystatechange = function() {

console.log('withCredentials=>', xhr.withCredentials);

};

xhr.send(null);

af1fc0fab4c5

配置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);

af1fc0fab4c5

虽然配置了拥有跨域访问权限,但是测试时的页面并不允许被当前域所调用,所以出现同源策略错误,下图所示为允许调用的示例:

var xhr = new XMLHttpRequest();

xhr.open('GET', 'http://172.19.0.215:1314/learnLinkManager/getLearnLinkList', true);

xhr.withCredentials = true;

xhr.onreadystatechange = function() {

console.log('withCredentials=>', xhr.withCredentials);

};

xhr.send(null);

af1fc0fab4c5

af1fc0fab4c5

需要注意是,当配置了xhr.withCredentials = true时,必须在后端增加 response 头信息Access-Control-Allow-Origin,且必须指定域名,而不能指定为*。当前示例所采用的node端配置代码:

res.setHeader('Access-Control-Allow-Origin','http://172.19.0.215:3333');

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

下图为同域下配置xhr.withCredentials = false的请求效果

af1fc0fab4c5

如果想了解更多的XMLHttpRequest参数,请查阅XMLHttpRequest参数详解

《野生前端工程师》专辑中所有文章均为@拭目以待 原创,转载请注明出处。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐