Vue封装axios的示例讲解

1、axios:是一个基于Promise的网络请求库。既可以在node.js(服务器端)使用,也可以在浏览器端使用

(1)在node.js中使用的原生的http模块

(2)在浏览器中使用的XMLHttpRequest

2、vue中的使用方法

(1)安装:npm install axios

(2)引用方法:

原生的方式(不推荐使用)

axios({
      url:'http://127.0.0.1:9001/students/test',  //远程服务器的url
      method:'get',  //请求方式
    }).then(res=>{
      this.students = res.data
    }).catch(e=>{
      console.error(e);
    })
//缺点:每个使用axios的组件都需要导入

注:axios对服务端数据的封装

  • res.config:响应信息的配置情况
  • res.data:响应的数据
  • res.headers:响应头信息(信息的大小、信息的类型)
  • res.request:请求对象
  • res.status:请求、响应的状态码
  • res.statusText:请求、响应状态码对应的文本信息

在项目的main.js文件中导入axios,将其写入Vue的原型中(推荐使用)

import axios from "axios";
Vue.prototype.$http = axios

在组件中通过this.$http的方式使用

this.$http.get('http://127.0.0.1:9001/students/test').then(res=>{
        this.students = res.data
      }).catch(e=>{
        console.log(e)
      })

缺点:只能在vue2使用,vue3中不能用

将axios单独封装到某个配置文件中(在配置文件中单独封装axios实例)

(1)配置文件:axiosApi.js

import axios from "axios";
const axiosApi = axios.create({
    baseURL:'http://127.0.0.1:9001', //基础地址
    timeout:2000        //连接超时的时间(单位:毫秒)
})
export default  axiosApi   //axiosApi是axios的实例

(2)使用:

import $http from '../config/axiosapi'
$http.get('/students/test').then(res=>{
        this.students = res.data.info
      }).catch(e=>{
        console.log(e)
      })

优点:既可以在vue2中使用,也可以在vue3中使用

3、axios的不同请求方式向服务器提交数据的格式:

(1)get请求:服务器端通过req.quert参数名来接收

直接将请求参数绑定在url地址上

let str = '张三'
      $http.get('/students/test/?username='+str).then(res=>{
        this.students = res.data.info
      }).catch(e=>{
        console.log(e)
      })

通过params方式进行提交

let str = '张三'
      $http.get('/students/test',{
        params:{
          username:str
        }
      }).then(res=>{
        this.students = res.data.info
      }).catch(e=>{
        console.log(e)
      })

(2)post方式请求:服务器端通过req.body.参数名获取数据

let str = '张三'
      $http.post('/students/test',{
        username:str
      }).then(res=>{
        this.students = res.data.info
      }).catch(e=>{
        console.log(e)
      })

(3)put方式请求:和post方式一样

(4)delete方式请求:和get方式一样

原文地址:https://blog.csdn.net/m0_73634593/article/details/128598980