【axios网络请求库】认识Axios库;axios发送请求、创建实例、创建拦截器、封装请求

目录

1_认识Axios库

功能特点:

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据

2_axios发送请求

支持多种请求方式:

  • axios(config)
  • axios.request(config)
  • axios.get(url, config)
  • axios.delete(url, config)
  • axios.head(url, config)
  • axios.post(url, data\[, config])
  • axios.put(url, data\[, config])
  • axios.patch(url, data\[, config])

有时候, 可能需求同时发送两个请求

  • 使用axios.all, 可以放入多个请求的数组.
  • axios.all(\[\]) 返回的结果是一个数组,使用 axios.spread 可将数组 res1,res2 展开为 res1, res2

常见的配置选项

(前三个选项常用)

  • 请求地址 url: '/user',

  • 请求类型 method: 'get',

  • 请求根路径 baseURL: 'http://www.mt.com/api',

  • 请求前的数据处理 transformRequest:function(data){},

  • 请求后的数据处理 transformResponse: function(data){},

  • 自定义的请求头 headers:{'x-Requested-With':'XMLHttpRequest'},

  • URL查询对象 params:{ id: 12 }

  • 查询对象序列化函数 paramsSerializer: function(params){ }

  • request body为 data: { key: 'aa'},

  • 超时设置 timeout: 1000,

demo1

js 复制代码
// 1.发送request请求
axios.request({
  url: "http://123.207.32.32:8000/home/multidata",
  method: "get"
}).then(res => {
  console.log("res:", res.data)
})

// 2.发送get请求
axios.get(`http://123.207.32.32:9001/lyric?id=500665346`).then(res => {
  console.log("res:", res.data.lrc)
})
axios.get("http://123.207.32.32:9001/lyric", {
  params: {
    id: 500665346
  }
}).then(res => {
  console.log("res:", res.data.lrc)
})


// 3.发送post请求
axios.post("http://123.207.32.32:1888/02_param/postjson", {
  data: {
    name: "coderwhy",
    password: 123456
  }
}).then(res => {
  console.log("res", res.data)
})

demo2

js 复制代码
// 1.baseURL
const baseURL = "http://123.207.32.32:8000"

// 给axios实例配置公共的基础配置
axios.defaults.baseURL = baseURL
axios.defaults.timeout = 10000
axios.defaults.headers = {}

// 1.get: /home/multidata
axios.get("/home/multidata").then(res => {
  console.log("res:", res.data)
})



// 2.axios发送多个请求
// Promise.all
axios.all([
  axios.get("/home/multidata"),
  axios.get("http://123.207.32.32:9001/lyric?id=500665346")
]).then(res => {
  console.log("res:", res)
})

3_axios创建实例

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

  • 当给该实例设置一些默认配置时, 这些配置就被固定下来了.
  • 但是后续开发中, 某些配置可能会不太一样;
  • 比如某些请求需要使用特定的baseURL或者timeout等.
  • 这时,就可以创建新的实例, 并且传入属于该实例的配置信息
js 复制代码
// axios默认库提供实例对象
axios.get("http://123.207.32.32:9001/lyric?id=500665346")

// 创建其他的实例发送网络请求
const instance1 = axios.create({
  baseURL: "http://123.207.32.32:9001",
  timeout: 6000,
  headers: {}
})

instance1.get("/lyric", {
  params: {
    id: 500665346
  }
}).then(res => {
  console.log("res:", res.data)
})

const instance2 = axios.create({
  baseURL: "http://123.207.32.32:8000",
  timeout: 10000,
  headers: {}
})

4_axios的拦截器

axios的也可以设置拦截器:拦截每次请求和响应

  • axios.interceptors.request.use(请求成功拦截, 请求失败拦截)
  • axios.interceptors.response.use(响应成功拦截, 响应失败拦截)

demo

js 复制代码
// 对实例配置拦截器
//【请求】
axios.interceptors.request.use((config) => {
  console.log("请求成功的拦截")
  // 1.开始loading的动画

  // 2.对原来的配置进行一些修改
  // 2.1. header
  // 2.2. 认证登录: token/cookie
  // 2.3. 请求参数进行某些转化

  return config
}, (err) => {
  console.log("请求失败的拦截")
  return err
})
//【响应】
axios.interceptors.response.use((res) => {
  console.log("响应成功的拦截")

  // 1.结束loading的动画

  // 2.对数据进行转化, 再返回数据
  return res.data
}, (err) => {
  console.log("响应失败的拦截:", err)
  return err
})

axios.get("http://123.207.32.32:9001/lyric?id=500665346").then(res => {
  console.log("res:", res)
}).catch(err => {
  console.log("err:", err)
})

5_axios请求封装

便于以后突发情况,比如axios库不再维护

js 复制代码
import axios from 'axios'

class HYRequest {
  constructor(baseURL, timeout=10000) {
    this.instance = axios.create({
      baseURL,
      timeout
    })
  }

  request(config) {
    return new Promise((resolve, reject) => {
      this.instance.request(config).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    })
  }

  get(config) {
    return this.request({ ...config, method: "get" })
  }

  post(config) {
    return this.request({ ...config, method: "post" })
  }
}

export default new HYRequest("http://123.207.32.32:9001")
相关推荐
明月_清风15 分钟前
Deno 终局来了:从挑战 Node 到被 Cloudflare 收编
前端·后端·node.js
Csvn1 小时前
框架性能优化
前端
回眸&啤酒鸭3 小时前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户69371750013843 小时前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员3 小时前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子3 小时前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒3 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend4 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
海码事务所5 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI5 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉