使用XMLHttpRequest发送请求无法携带Cookie
最近在项目里设计了一段JS,需要客户网站嵌入这段JS,然后使用XMLHTTPRequest发送请求,但是发现请求中无法携带Cookie。
经过研究发现XMLHTTPRequest发送请求是无法携带Cookie的,即使使用了setRequestHeader方法是设置请求头里的cookie,也无法携带cookie。
var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Cookie', 'mycookie=cookie');
所以就想到可以在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));
}