• vue3项目实战中的接口调用方法(二)fetch用法 (前后端交互) get请求/post请求/put请求/delete请求


    🔥点击进入vue专栏🔥

    上期推文中讲述了vue3项目实战中接口调用的方法(一)🔥点击即可复习🔥,介绍了async/await调用接口的过程和方法
    从本期文章开始将会不定时更新 vue3项目实战中接口调用的三大方法。👏👏👏本期文章将重点介绍vue3的 fetch方法实现请求接口
    (👏👏👏欢迎大佬们多多指教!)

    fetch概述

    基本特性

    • fetch是传统ajax的升级版本,并不是对ajax的进一步封装,是原生js
    • fetch是新的ajax解决方案,fetch会返回Promise
    • 更加简单的数据获取方式,功能更强大,更灵活,可以看作是XMLHttpRequest的升级版。
    • fetch(url,options).then()

    🔥语法结构

    fetch(url).then(fn2)
    		 .then(fn3)
    		 ...
    		 .then(fn)
    
    • 1
    • 2
    • 3
    • 4

    示例:
    在这里插入图片描述源码:

    <script type="text/javascript">
        // Fetch API 基本用法 fetch(url).then() 第一个参数请求的路径
        // Fetch会返回Promise 所以我们可以使用then 拿到请求成功的结果
        fetch('http://localhost:3000/fdata').then(function(data){
            // text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,
            // 用于获取后台返回的数据 return data.text();
            return data.text();
        }).then(function (data) {
            // 在这个then里面我们能拿到最终的数据
            console.log(data);
        })
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    fetch基本用法

    • 第一个.then接收到的是Promise数据集
    • 需要被.then处理才可以看到我们最终想要的数据。

    基本写法:

    fetch('/abc').then(data=>{
        return data.text();
    }).then(ret=>{
        // 【注意】这里得到的才是最终的数据
        console
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    示例:
    在这里插入图片描述
    源码:

    // 客户端请求
    <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!')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    控制台显示:
    在这里插入图片描述

    fetch的HTTP请求🔥🔥

    常用配置选项

    • method(String):HTTP请求方法,默认为GET HTTP提供了很多方法(GET、DELETE、POST、PUT
    • body(String):HTTP请求参数
    • headers(Object):HTTP的请求头,默认为{}
    • fetch(url, options).then()
    • 需要在options对象中,指定对应的methodmethod:请求使用的方法。
    • post和普通请求的时候,需要在options中设置请求头headersbody

    get请求🔥

    way1:传统的URL传递参数
    在这里插入图片描述
    源码:(含详细注释

    // 客户端请求
    <body>
      <script type="text/javascript">
      // GET参数传递-传统URL 通过URL ? 的形式传参
        fetch('http://localhost:3000/books?id=123', {
          method: 'get' // 当请求方式为get时 可以省略不写 因为请求方式默认为get
        })
          .then(function(data){
          // 返回一个Promise实例对象 用于获取后台返回的数据
            return data.text();
          }).then(function(data){
          // 在这个then里面我们能够拿到最终的数据
            console.log(data)
          });
      </script>
    </body>
    
    // 服务器响应
    app.get('/books', (req, res) => {
      res.send('传统的URL传递参数!' + req.query.id)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    控制台结果:
    在这里插入图片描述

    way2:restful形式的URL
    在这里插入图片描述
    源码:

    // 客户端请求
    <body>
      <script type="text/javascript">
      // GET参数传递  restful形式的URL 通过/ 的形式传递参数 即 id = 456 和 id的后台配置有关
        fetch('http://localhost:3000/books/456', {
          method: 'get' // 默认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)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    控制台结果:
    在这里插入图片描述

    delete请求

    示例一:
    在这里插入图片描述
    源码:(含详细注释

    // 客户端请求
    <body>
      <script type="text/javascript">
        // DELETE请求方式参数传递 删除id 是 id = 789
        fetch('http://localhost:3000/books/789', {
          method: 'delete' // 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)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    控制台结果:
    在这里插入图片描述

    post请求🔥

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

    way1 传递的是传统格式的参数
    示例:
    在这里插入图片描述
    源码:

    // 客户端请求
    <body>
      <script type="text/javascript">
        // POST请求传参
        fetch('http://localhost:3000/books', {
          method: 'post', // 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)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    控制台结果:
    在这里插入图片描述

    way2: 传递的是json的参数
    在这里插入图片描述
    源码:

    // 客户端请求
    <body>
      <script type="text/javascript">
        // POST请求传参
        fetch('http://localhost:3000/books', {
          method: 'post',
          body: JSON.stringify({ // json格式的参数uname pwd
            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)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    控制台结果:
    在这里插入图片描述
    在这里插入图片描述

    put请求方式🔥

    • put请求方式的参数传递:一般提交的数据,用于修改原有数据
    • put也支持第一种,传递传统表单text形式的参数
    • json格式需要后台提供支撑

    示例:
    在这里插入图片描述

    源码:

    // 客户端请求
    <body>
      <script type="text/javascript">
        // PUT请求传参 修改id 是 123 的
        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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    控制台结果:
    在这里插入图片描述

    fetch响应结果/格式

    • text():将返回体处理成字符串类型
    • json():返回结果和JSON.parse(responseText)一样

    🔥text数据格式
    在这里插入图片描述
    控制台结果:
    在这里插入图片描述
    由于data为字符串类型的数据,无法直接访问该属性的值。
    修改方式如下:👇👇👇

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

    在这里插入图片描述

    🔥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'
      });
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

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

    在这里插入图片描述
    在这里插入图片描述

    summary

    以上就是关于vue3项目实战中调用接口的方法(二)fetch的全部内容。
    fetch虽没有现在流行的async await用起来方便简单,但是在接口调用中仍然占据重要方法的地位。
    (后期将会对最后一个方法axios进行讲述,完结vue的接口调用方法)

  • 相关阅读:
    Python基础——简介
    第7/100天 阅读笔记
    mybatis核心配置文件
    2023年全球及中国小分子化药CDMO市场发展概况分析:CDMO市场有望进一步扩大[图]
    js实现图片懒加载
    nacos配置中心源码分析——拉取配置信息
    【微服务】SpringCloud微服务剔除下线源码解析
    网络安全(黑客)自学
    云存储服务OneDrive捆绑系统销售,30多家欧洲公司投诉微软垄断
    传统用户管理方案有哪些利弊?
  • 原文地址:https://blog.csdn.net/XSL_HR/article/details/127452515