解决非同源跨域不带cookie问题(原生、axios、fetch写法)

发布时间 2023-07-24 17:11:40作者: 风花一世月

原生js写法

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:7001/api/userinfo', true);
xhr.withCredentials = true; // 开启withCredentials
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log("请求登录状态",xhr.responseText);
    }
};

 

 xhr.send();

 

axios写法
axios({
method: 'get',
url: 'http://localhost:7001/api/userinfo',
withCredentials: true, // 跨域请求时发送Cookie
})
.then(function (response) {
    console.log("请求登录状态",response);
});
fetch写法:(fetch要使用credentials)
fetch('http://localhost:7001/api/userinfo',{
    method: 'GET',
    credentials:"include"
}).then((response)=>response.json(),(error)=>{
//处理错误
}).then(json=>{
    console.log("请求登录状态",json);
})

 也可以使用iframe嵌入页面postMessage传递数据