欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-09 16:58:53
先看一段代码:fetch('http://localhost:3000/books?id=123456',{ method:'get'}).then(function(value1){ c...

先看一段代码:

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

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

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

那么现在去掉注释:

vue fetch中的.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));
})

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

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

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