使用XMLHttpRequest发送请求无法携带Cookie

使用XMLHttpRequest发送请求无法携带Cookie

最近在项目里设计了一段JS,需要客户网站嵌入这段JS,然后使用XMLHTTPRequest发送请求,但是发现请求中无法携带Cookie。

经过研究发现XMLHTTPRequest发送请求是无法携带Cookie的,即使使用了setRequestHeader方法是设置请求头里的cookie,也无法携带cookie。

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Cookie', 'mycookie=cookie');

原因如下:https://stackoverflow.com/questions/15198231/why-cookies-and-set-cookie-headers-cant-be-set-while-making-xmlhttprequest-usin

所以就想到可以在JS里面动态插入一个Pixel(一个长宽为1的img标签,src属性为请求的URL)来发送请求,能成功携带cookie,示例代码如下:

var imgTag = document.createElement('img');
var bodyTag = document.getElementsByTagName('body')[0];
imgTag.height = 1;
imgTag.width = 1;
imgTag.style = 'border-style: none; display: none';
imgTag.alt = '';
imgTag.src = tbUrl;    //你要发请求的url

bodyTag.insertBefore(imgTag, bodyTag.childNodes[0]);

另外 还可以在请求头里面加入withCredentials: true来实现:

function postJson(url, data, isWithCredentials) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState === 4 && xmlHttp.status === 200)
            console.log(xmlHttp.responseText);
    };
    xmlHttp.open("POST", url, true); // true for asynchronous
    if (isWithCredentials === true) {
        xmlHttp.withCredentials = true;
    }
    xmlHttp.send(JSON.stringify(data));
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值