ajax中的withCredentials使用效果

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

在这里插入图片描述
配置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);

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

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

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

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

同时,后端需要配置:

xhr.withCredentials = true

如果在同域下配置xhr.withCredentials,无论配置true还是false,效果都会相同,且会一直提供凭据信息(cookie、HTTP认证及客户端SSL证明等)
下图为同域下配置xhr.withCredentials = false的请求效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值