![8b78a7e8b54bed69c26dac38031f8c18.png](https://i-blog.csdnimg.cn/blog_migrate/fcf85c0edd625e9a4c80a3932f890549.jpeg)
withCredentials可以在跨域的时候带上cookie,我们现在来看看在不同的写法中如何配置withCredentials:
原生js
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.withCredentials = true; // 设置运行跨域操作
xhr.send();
xhr.onload = () => {
const text = xhr.responseText;
if (xhr.status === 200) {
resolve(JSON.parse(text));
} else {
let error = new Error(text);
error.response = xhr;
reject(error);
}
};
jquery
$.ajax({
url : 'xxx',
xhrFields: {
withCredentials: true // 设置运行跨域操作
},
success : function(data) {
console.log(data);
}
});
fetch
export function Get(url) {
const config = {
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include'
};
return fetch(url, config)
.then(checkStatus)
.then(parseJSON);
}
axios.js
axios(url, {
method: 'GET',
mode: 'no-cors',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
withCredentials: true,
credentials: 'same-origin',
}).then(response => {
})