vue fetch中的.then()的正确使用方法

您所在的位置:网站首页 then vue fetch中的.then()的正确使用方法

vue fetch中的.then()的正确使用方法

2023-01-05 14:07| 来源: 网络整理| 查看: 265

先看一段代码:

fetch('http://localhost:3000/books?id=123456',{ method:'get' }) .then(function(value1){ console.log(value1); return 'hello'; }) .then(function(value2){ console.log(value2); return 'HelloWorld'; }) /* .then(function(data){ console.log(data); return data.text(); }) */ .then(data=>{ console.log(data); }) // 接口 app.get('/books', (req, res) => { res.send('传统的URL传递参数!' + req.query.id) })

在这段代码中我们发现,最初传入的是一个对象,紧接着后一个.then()的传入参数使用了前一个.then()的返回值,换句话说,就是后一个then使用前一个then的封装结果

那么现在去掉注释:

.then(function(value2){ console.log(value2); return 'HelloWorld'; }) .then(function(data){ console.log(data); return data.text(); }) text()方法属于fetch API的一部分,返回一个Promise实例对象,用于获取后台返回的数据

这段代码中,传入的data是上一步封装的字符串,所以此时用data.text()报错,除非data为对象

下面演示正确使用方式:

fetch('http://localhost:3000/books?id=123456',{ method:'get' }) .then(function(data){ console.log(data); console.log(typeof(data)); return data.text(); }) .then(data=>{ console.log(data); console.log(typeof(data)); })

输出了接口询问的内容,为String类型

到此这篇关于vue fetch中的.then()的正确使用方法的文章就介绍到这了,更多相关vue fetch .then()内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:Vue的export default和带返回值的data()及@符号的用法说明详解Vue返回值动态生成表单及提交数据的办法详解vue中this.$emit()的返回值是什么vue中then后的返回值解析


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3