irpas技术客

Fetch发送请求 + 解决跨域问题_吃不到棒棒糖的小熊_fetch 跨域

未知 7022

目录

fetch的基本用法:

使用fetch发送get请求:

使用fetch发送post请求:

解决跨域问题:


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(); })


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #fetch #跨域