Vue接口调用(一)fetch用法

Vue接口调用🔥

接口调用地址
Vue接口调用(一)fetch用法https://blog.csdn.net/m0_55990909/article/details/123957200
Vue接口调用(二)axios用法🔥https://blog.csdn.net/m0_55990909/article/details/123981283
Vue接口调用(三)async/await用法🔥https://blog.csdn.net/m0_55990909/article/details/123981292

目录总览:

1. fetch概述

基本特性

  • fetch是传统ajax的升级版本,是原生js
  • 更加简单的数据获取方式,功能更强大,更灵活,可以看作是xhr的升级版。
  • 基于Promise实现

语法结构

fetch(url).thne(fn2)
		 .thne(fn3)
		 ...
		 .then(fn)
2. fetch的基本用法
  • 第一个.then接收到的是Promise数据集
  • 需要被.then处理才可以看到 我们最终想要的数据。

//客户端请求
<body>
  <script type="text/javascript">
    //Fetch API 基本用法
    fetch('http://localhost:3000/fdata').then(function(data){
      // text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
      return data.text();
    }).then(function(data){
      console.log(data);
    })
  </script>
</body>

//服务器响应
app.get('/fdata', (req, res) => {
  res.send('Hello Fetch!')
})

3. fetch请求参数

常用配置选项:

  • method(String):HTTP请求方法,默认为GET(GET、DELETE、POST、PUT)
  • body(String):HTTP请求参数
  • headers(Object):HTTP的请求头,默认为{}
3.1 get请求方式的参数传递
第一种方式
//客户端请求
<body>
  <script type="text/javascript">
  //GET参数传递-传统URL
    fetch('http://localhost:3000/books?id=123', {
      method: 'get'
    })
      .then(function(data){
        return data.text();
      }).then(function(data){
        console.log(data)
      });
  </script>
</body>

//服务器响应
app.get('/books', (req, res) => {
  res.send('传统的URL传递参数!' + req.query.id)
})

第二种方式(restful形式的url)
//客户端请求
<body>
  <script type="text/javascript">
  //GET参数传递 - restful形式的URL
    fetch('http://localhost:3000/books/456', {
      method: 'get'
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服务器响应
app.get('/books/:id', (req, res) => {
  res.send('Restful形式的URL传递参数!' + req.params.id)
})

3.2 delete请求方式的参数传递
//客户端请求
<body>
  <script type="text/javascript">
    //DELETE请求方式参数传递
    fetch('http://localhost:3000/books/789', {
      method: 'delete'
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服务器响应
app.delete('/books/:id', (req, res) => {
  res.send('DELETE请求传递参数!' + req.params.id)
})

3.3 post请求方式的参数传递
  • body用于向后台传递数据
  • headers请求头需要配置content-type内容类型(后面的值是固定的),才可以传过去
第一种方式

传递的是传统格式的参数

//客户端请求
<body>
  <script type="text/javascript">
    //POST请求传参
    fetch('http://localhost:3000/books', {
      method: 'post',
      body: 'uname=lisi&pwd=123',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服务器响应
app.post('/books', (req, res) => {
  res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
})

第二种方式

传递的是Json格式的参数

//客户端请求
<body>
  <script type="text/javascript">
    //POST请求传参
    fetch('http://localhost:3000/books', {
      method: 'post',
      body: JSON.stringify({
        uname: '张三',
        pwd: '456'
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服务器响应
app.post('/books', (req, res) => {
  res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
})

  • 可以接受json格式参数的原因:有bodypaser中间键

3.4 put请求方式的参数传递
  • put请求方式的参数传递:一般提交的数据,用于修改原有数据
    • put也支持第一种 传递传统表单text形式的参数
    • json格式需要后台提供支撑,也就是bodyParser中间键
//客户端请求
<body>
  <script type="text/javascript">
    //PUT请求传参
    fetch('http://localhost:3000/books/123', {
      method: 'put',
      body: JSON.stringify({
        uname: '张三',
        pwd: '789'
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(function (data) {
        return data.text();
      }).then(function (data) {
        console.log(data)
      });
  </script>
</body>

//服务器响应
app.put('/books/:id', (req, res) => {
  res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

4. fetch响应结果
  • text():将返回体处理成字符串类型
  • json():返回结果和JSON.parse(responseText)一样
第一种方式text
//客户端请求
<body>
  <script type="text/javascript">
    //Fetch响应text数据格式
    fetch('http://localhost:3000/json').then(function(data){
      return data.text();
    }).then(function(data){
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })
  </script>
</body>

//服务器响应
app.get('/json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 13,
    gender: 'male'
  });
})
  • data类型为字符串,无法直接访问属性的值

处理方式(访问到具体属性值):

1.使用JSON.parse()把字符串转化成对象
var obj = JSON.parse(data)
2.使用 obj.属性名 得到属性值
console.log(obj.uname)

第二种方式json
//客户端请求
<body>
  <script type="text/javascript">
    //Fetch响应json数据格式
    fetch('http://localhost:3000/json').then(function(data){
      return data.json();
    }).then(function(data){
      console.log(data.uname)
    })
  </script>
</body>

//服务器响应
app.get('/json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 13,
    gender: 'male'
  });
})

  • 返回的data是object对象,可以直接获取对象中属性的值 (data.属性名)

  • 6
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 接口调用顺序执行的方式有多种,以下是其中的一些示例: 1. 使用 async/await 可以在 Vue 的 methods 中使用 async/await,确保按顺序执行异步方法。例如: ```javascript methods: { async fetchData1() { // 异步获取数据的方法1 }, async fetchData2() { // 异步获取数据的方法2 }, async fetchData() { await this.fetchData1(); await this.fetchData2(); // 执行完 fetchData1 后再执行 fetchData2 } } ``` 2. 使用 Promise 可以将异步方法封装成 Promise,再使用 Promise 的链式调用,确保按顺序执行。例如: ```javascript methods: { fetchData1() { return new Promise(resolve => { // 异步获取数据的方法1 resolve(); }); }, fetchData2() { return new Promise(resolve => { // 异步获取数据的方法2 resolve(); }); }, fetchData() { this.fetchData1().then(() => { return this.fetchData2(); }).then(() => { // 执行完 fetchData1 后再执行 fetchData2 }); } } ``` 3. 使用 async/await 和 Promise 的结合 使用 async/await 和 Promise 的结合,可以更方便地写出顺序执行的代码。例如: ```javascript methods: { fetchData1() { return new Promise(resolve => { // 异步获取数据的方法1 resolve(); }); }, fetchData2() { return new Promise(resolve => { // 异步获取数据的方法2 resolve(); }); }, async fetchData() { await this.fetchData1(); await this.fetchData2(); // 执行完 fetchData1 后再执行 fetchData2 } } ``` 以上是几种常用的 Vue 接口调用顺序执行的方式,可以根据具体的需求选择适合自己的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值