es6的新语法fetch(使用koa项目测试)
说起fetch新语法,你或许不知道他是干嘛的,到底有什么用?
如果在此之前你如果了解了ajax和axios,由ajax到axios再到fetch,恭喜你,fetch新语法你很快就可以入门了。
ajax和axios给人的第一印象不都是用来发起数据请求的吗?不是发送get请求就是发送post请求,你如果这样理解起来也没错。
接下来我们谈谈es6的fetch新语法。
fetch新语法:fetch是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。不过fetch新语法可不是Ajax的进一步封装,而是原生JS。
什么叫原生?原生就是不需要引入。
fetch函数就是原生JS,没有使用XMLHttpRequest对象,不像axios,想要使用axios还需要作第三方的引入。
简单点理解呢,fetch新语法就是es6提供给我们前后端交互的一种方式,它是一种全新的API,这种API是一种未来的趋势,它在未来可能取代ajax,此外,它是基于Promise来实现的。
fetch基本格式,用法类似axios:

如上图,fetch()函数里面写上一个请求的url,当请求成功的时候就会触发.then()函数,在then里面会返回一个res,这个res就是返回的response对象,但在这个response对象下我们是没办法直接拿到数据的,需要使用res.json()方法来转译出一个promise对象,这个promise对象再去执行.then()函数才能拿到data数据。
fetch优势:
- 语法简洁,更加语义化(不像ajax要写一堆代码)
- 基于标准Promise实现,支持async和await
- 脱离了XHR,是ES规范里新的实现方式
- 无需引入第三方插件(axios是要引入的)
- 未来可能成为一种规范
代码案例:fetch默认发起的是一个get请求
fetch发起请求数据,拿对象类型的数据
<script type="text/javascript">
fetch('/json')
.then(res =>{
return res.json()
})
.then(data =>{
console.log(data)
})
</script>
接口代码:返回对象形式的数据给客户端
router.get('/json', async (ctx, next) => {
ctx.body = {
name: '王维'
}
})
浏览器拿到的响应结果

fetch发起请求数据,拿字符串类型的数据
<script type="text/javascript">
fetch('/json')
.then(res =>{
return res.text()
})
.then(data =>{
console.log(data)
})
</script>
接口代码:返回字符串形式的数据给客户端
router.get('/json', async (ctx, next) => {
ctx.body = '落霞与孤鹜齐飞,秋水共长天一色'
})
浏览器拿到的响应结果

get请求携带查询字符串
<script type="text/javascript">
fetch('/json?user=覃')
.then(res =>{
return res.text()
})
.then(data =>{
console.log(data)
})
</script>

fetch发起POST请求
<script type="text/javascript">
fetch('/goods',{
method:'POST'
})
.then(res =>{
return res.json()
})
.then(data =>{
console.log(data)
})
</script>
接口代码:
router.post('/goods', async (ctx, next) => {
ctx.body = {
id:'001',
title:'液晶电视',
pirce:'¥1999',
size:'100寸大屏'
}
})
POST请求回来的结果:


POST请求发送JSON数据
<script type="text/javascript">
fetch('/goods',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({"user":"张伟"})
})
.then(res =>{
return res.json()
})
.then(data =>{
console.log(data)
})
</script>
接口:
router.post('/goods', async (ctx, next) => {
console.log(ctx.request.body)//获取前端post过来的数据
ctx.body = {
id:'001',
title:'液晶电视',
pirce:'¥1999',
size:'100寸大屏'
}
})
看一下前台数据有没有没传过去给后端。

查看一下后端有没有接收到前台post过来的数据。

fetch本身存在的一些小问题
404、500等会触发Promise的成功状态
fetch新语法是没有catch()捕捉报错返回的,所以当我们发起一个不存在的请求url时,依旧会走then,因为fetch里面没有catch这条路。
fetch('/goods111111111111',{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({"user":"张伟"})
})
.then(res =>{
console.log(res)
//return res.json()
})
.then(data =>{
console.log(data)
})
</script>
但是控制台是可以捕捉到报错信息的,主要看ok字段和和status字段的返回值。

功能相对薄弱、没有取消请求、超时、进度等功能
axios完全可以实现。
相比axios在使用上略显复制
需要设置请求头headers和使用JSON.stringify()进行转译

兼容性差
拓展:
