代码改变世界

Fetch发送请求 + 解决跨域问题

2022-09-28 13:33  狼人:-)  阅读(1810)  评论(0编辑  收藏  举报

 

 

 

 

 

解决跨域问题:

fetch()方法提供了一种简单,合理的方式来跨网络异步获取资源。

可以使用fetch向服务器发送get请求或post请求来获取数据

fetch的基本用法:
fetch('/url').then(data=>{
return data.text();
}).then(ret=>{
//注意,这里才是得到的最终数据
console.log(ret);
});
使用fetch发送get请求:
把参数拼接在url中传递过去

text():将返回体处理成字符串类型

json():返回结果和JSON.parse(responseText)一样

fetch('http://localhost:3001/user/login?username='+zhanghao+'&&password='+mima)
.then(function (response) {
return response.text();
})
.then(function (myJson) {
alert(myJson);
});
使用fetch发送post请求:
fetch('http://localhost:3001/admin/add', {
method: 'post',
body:JSON.stringify(obj),
headers:{
'Content-Type': 'application/json'
}
})
.then(function (response) {
return response.text();
})
.then(function (myJson) {
alert(myJson);
});
解决跨域问题:
在服务器端添加 Response Header

如果服务器返回的 response 头包含 “Access-Control-Allow-Origin:*” 或者 *为与请求源相同的地址。即服务器支持浏览器跨域访问。

app.all("*",function(req,res,next){

res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");

next();
})

————————————————
版权声明:本文为CSDN博主「吃不到棒棒糖的小熊」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_59897687/article/details/124346869