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

原生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传递数据

posted @   风花一世月  阅读(113)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示