栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

目录

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829947.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号