四、【React脚手架】扩展:fetch发送请求

首先认清一个辈分:

  • xhr
    • jquery
    • axios
  • fetch

fetch 和 xhr 的同一个辈分的!!!且window内置了fetch,不用安装任何插件即可使用!且fetch本身就是promise风格的!

1、特点

  1. fetch: 原生函数,不再使用XmlHttpRequest对象提交ajax请求
  2. 老版本浏览器可能不支持

2、相关API

2.1、Get

fetch(url).then(function(response) {
    return response.json()
}).then(function(data) {
    console.log(data)
}).catch(function(e) {
    console.log(e)
});

2.2、Post

fetch(url, {
    method: "POST",
    body: JSON.stringify(data),
}).then(function(data) {
    console.log(data)
}).catch(function(e) {
    console.log(e)
})

3、Demo

三、【React脚手架】React Ajax(axios) 的 axios 做对比,代码如下:

// axios
axios.post('http://localhost:8003/tBannerHtml/selectBanner').then(
    response => {
        console.log(`请求成功,返回参数:`, response.data)
    },
    error => {
        console.log(`请求失败,失败原因:`, error)
    }
)

// fetch(常规)
fetch('http://localhost:8003/tBannerHtml/selectBanner').then(
    response => {
        console.log(`联系服务器成功了`)
        return response.json()
    },
    error => {
        console.log(`联系服务器成功了,失败原因:`, error)
        return new Promise(()=>{})
    }
).then(
    response => {
        console.log(`获取数据成功了:`, response)
    },
    error => {
        console.log(`获取数据失败了:`, error)
    }
)

// fetch(优化)
fetch('http://localhost:8003/tBannerHtml/selectBanner').then(
    response => {
        console.log(`联系服务器成功了`)
        return response.json()
    }
).then(
    response => {
        console.log(`获取数据成功了:`, response)
    }
).catch( // 统一处理错误
	error => {
		console.log('请求出错:', error)
	}
)

// fetch(再优化)
try {
	const response = await fetch('http://localhost:8003/tBannerHtml/selectBanner')
	const data = await response.json()
	console.log(`获取数据成功了:`, data )
} catch ( error ) {
	console.log('请求出错:', error)
}


参阅文档:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纯纯的小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值