网络请求的封装

1、Vue中选择什么网络模块?#

Vuex中发送网络请求有非常多的方式

1)传统的Ajax是基于XMLHttpRequest(XHR)

为什么不使用?

配置和调用方式非常混乱,所以在开发中很少使用,而是使用 jquery-ajax


2)jquery-ajax

为什么不使用?

首先我们需要明确一点,在vue的整个开发中是不需要使用 jquery的,

那么意味着为了方便我们进行一个网络请求,特意引入一个重量级的框架jquery,得不偿失


3)axios

axios有非常多的优点,并且使用起来也非常的方便

① 在浏览器中发送 XMLHttpRequests请求

② 在node.js中发送 http 请求

③ 支持Promise API

④ 拦截请求和响应

⑤ 转换请求和响应数据


2、axios框架的基本使用#

复制代码
axios({
  url: 'http://123.207.32.32:8000/home/mutidata'
  //method: 'get'/'post'
}).then(res => {
  console.log(res)
})

//axios的get请求
//1) 参数直接跟在url上
axios({
  url: 'http://123.207.32.32:8000/home/mutidata'
}).then(res => {
  console.log(res)
})

//2) 多个参数放在url中
axios({
  url: 'http://123.207.32.32:8000/home/data',
  params: {
    type: 'pop',
    page: 1
  }
}).then(res => {
  console.log(res)
})

//3、使用axios.get - 参数写在url中
axios.get('http://123.207.32.32:8000/home/mutidata')
.then(res=>{
  console.log(res)
})

//4、使用axios.get - 参数写在params中
axios.get('http://123.207.32.32:8000/home/data',
  {
    params: {
      type: 'pop',
      page: 1
    }
  }).then(res => {
    console.log(res)
})
复制代码


3、axios发送并发请求#

复制代码
//axios发送并发请求
//axios.all([axios(),axios()]).then(res => {})
// res是一个数组,包含每条请求的结果
axios.all([axios({
  url: 'http://123.207.32.32:8000/home/mutidata'
}),axios({
  url: 'http://123.207.32.32:8000/home/data',
  params: {
    type: 'pop',
    page: 1
  }
})])
  .then(res => {
    console.log(res);
    console.log(res[0]);
    console.log(res[1]);
  })
复制代码


对结果进行一层处理:

复制代码
axios.all([axios({
  url: 'http://123.207.32.32:8000/home/mutidata'
}),axios({
  url: 'http://123.207.32.32:8000/home/data',
  params: {
    type: 'pop',
    page: 1
  }
})])
  .then(axios.spread((res1,res2) => {
    console.log(res1);
    console.log(res2);
}))
复制代码


4、axios的配置信息相关#

事实上,在开发中很多参数是固定的,这个时候我们可以进行一些抽取,也可以利用axios的全局配置

复制代码
axios.defaults.baseURL = 'http://123.207.32.32:8000'
axios.defaults.timeout = 5000
axios.get('/home/data',
  {
    params: {
      type: 'pop',
      page: 1
    }
  }).then(res => {
  console.log(res)
})
复制代码

常见的配置选项:

clipboard


5、axios的实例和模块封装#

1)为什么要创建axios的实例?

当我们从axios模块中导入对象时,使用的实例是默认的实例

当给该实例设置一些默认的配置时,这些配置就被固定下来了

但是在后续的开发中,某些配置又可能不太一样,比如某些请求需要使用特定的baseURL,timeout或者content-Type 等

这个时候,我们可以创建新的实例,并且传入该实例的配置信息


2)如何创建axios的实例

复制代码
//创建对应的 axios 的实例
const instance1 = axios.create({
  baseURL: 'http://123.207.32.32:8000',
  timeout: 5000
})

instance1({
  url: '/home/multidata',
}).then( res => {
  console.log(res);
})
复制代码


3)为什么要进行模块封装?

减少项目各个文件处对第三方框架的依赖,当需要替换框架时,只需要修改你自己封装的文件

,非常方便


4)如何封装 axios请求

第一种方式:传入成功和失败的回调函数

封装 request.js

复制代码
import axios from "axios";

export function request(config,success,failure) {
  //1、创建axios的实例
  const instance = axios.create({
    baseURL: 'http://123.207.32.32:8000',
    timeout: 5000
  })

  //发送真正的网络请求
  instance(config).then(
    res => {
      success(res); //成功的回调函数
    }
  ).catch(err => {
    failure(err); //失败的回调函数
  })
}
复制代码

调用

复制代码
//5、封装request模块
import {request} from "./network/request";

request({
  url: "/home/mutidata"
},res=>{
  console.log(res);
},err => {
  console.log(err);
})
复制代码


第二种方式:使用Promise

复制代码
//使用 promise 进行封装
export function request(config,success,failure) {
  //1、创建axios的实例
  return new Promise((resolve,reject) => {
    const instance = axios.create({
      baseURL: 'http://123.207.32.32:8000',
      timeout: 5000
    })
    //发送真正的网络请求
    instance(config).then(
      res => {
        resolve(res); //成功的回调函数
      }
    ).catch(err => {
      reject(err); //失败的回调函数
    })
  })
}
复制代码


第三种方式:直接返回 instance(config)

因为axios本身就是一个promise

复制代码
export function request(config,success,failure) {
  //1、创建axios的实例
  const instance = axios.create({
    baseURL: 'http://123.207.32.32:8000',
    timeout: 5000
  })

  return instance(config);
}
复制代码


6、axios拦截器的使用#

axios提供了拦截器,用于在发送每次请求或者得到响应后,进行对应的处理。

如何使用拦截器?

复制代码
export function request(config,success,failure) {
  //1、创建axios的实例
  const instance = axios.create({
    baseURL: 'http://123.207.32.32:8000',
    timeout: 5000
  })

  //2.axios的拦截器
  //2.1 请求拦截
  axios.interceptors.request.use(config =>{
    console.log(config);
    //做一些操作
    //1、比如config的信息不符合服务器的要求,要对config做一些处理

    //2、比如每次发送网络请求时,都希望在界面中显示一个请求的图标

    //3、某些网络请求必须携带一些特殊的信息

    return config;
  },err => {
    console.log(err);
  })

  //2.2 响应拦截
  axios.interceptors.response.use(res => {
    console.log(res);
    return res.data;
  },error => {
    console.log(error);
  })
  return instance(config);
}
复制代码
posted @   青岑  阅读(218)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2019-04-08 获得类的字节码对象的三种方式
点击右上角即可分享
微信分享提示
主题色彩