前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >解决非同源跨域不带cookie问题(原生、axios、fetch写法等)

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

作者头像
风花一世月
发布2024-03-19 14:12:13
980
发布2024-03-19 14:12:13
举报
文章被收录于专栏:前端前端

原生js写法

代码语言:javascript
复制
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);
    }
};

axios写法

代码语言:javascript
复制
axios({
method: 'get',
url: 'http://localhost:7001/api/userinfo',
withCredentials: true, // 跨域请求时发送Cookie
})
.then(function (response) {
    console.log("请求登录状态",response);
});

fetch写法:(fetch要使用credentials)

代码语言:javascript
复制
fetch('http://localhost:7001/api/userinfo',{
    method: 'GET',
    credentials:"include"
}).then((response)=>response.json(),(error)=>{
//处理错误
}).then(json=>{
    console.log("请求登录状态",json);
})

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-07-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档