8. axios的使用与封装

69 阅读2分钟

一、认识axios

功能特点:

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

二、axios发送网络请求

1.常见请求演练

1.发送request请求

axios.request({
  url: "http://123.207.32.32:8000/home/multidata",
  method: "get"
}).then(res => {
  // 返回值:config data headers request status statusText
  console.log("res:", res.data);
})

2.发送get请求

axios.get("http://www.httpbin.org/get").then(res=>{
  console.log("res:",res.data);
})

axios.get("http://www.httpbin.org/get", {
  params: {
    id: 500665346
  }
}).then(res=>{
  console.log("res:",res.data);
})

3.发送post请求

axios.post("http://www.httpbin.org/post", {
  name: "wx",
  password: "123456"
}).then(res=>{
  console.log("res", res.data);
})

axios.post("http://www.httpbin.org/post", {
  data: {
    name: "wx",
    password: "123456"
  }
}).then(res=>{
  console.log("res", res.data);
})

2.配置和all

// 1.baseUrl
const baseURL = 'http://123.207.32.32:8000'

// 给axios实例配置公共的基础配置
axios.defaults.baseURL = baseURL

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

// 2.axios.all([])
//   + 可以放入多个请求的数组
//   + 返回的结果是一个数组,使用axios.spread可将数组[res1,res2]展开为res1, res2
axios.all([
  axios.get("/home/multidata"),
  axios.get("http://www.httpbin.org/get")
]).then(res=>{
  console.log("res:", res);
})

三、axios创建实例

// axios默认提供给我们的实例对象
axios.get("...")

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

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

const instance2 = axios.create({
  baseURL: "ss",
  timeout: 10000,
  headers: {}
})

四、axios的拦截器

// 给实例配置拦截器
// axios.interceptors.request.use(请求成功的回调拦截,请求失败的回调拦截)
axios.interceptors.request.use((config)=>{
  console.log("请求成功的拦截");
  // 1.显示loading的动画

  // 2.对原来的配置进行一些修改
  // 2.1 header
  // 2.2 认证登录: token/cookie
  return config
}, (err)=>{
  console.log("请求失败的拦截");
})
axios.interceptors.response.use((res)=>{
  console.log("响应成功的拦截");
  // 1.结束loading的动画
  // 2.对数据进行转化,再返回数据
  return res.data
},(err)=>{
  console.log("响应失败的拦截");
})

axios.get("http://www.httpbin.org/get").then(res=>{
  console.log("res:",res.data);
})


五、axios请求简单封装

封装简易HYRequest

import axios from 'axios'

class HYRequest {
  constructor(baseURL, timeout = 1000) {
    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, methods: "get" })
  }
  post(config) {
    return this.request({ ...config, methods: "post" })
  }
}

// const instance1 = new HYRequest("http://www.httpbin.org")
// const instance2 = new HYRequest("http://www.httpbins.org")

export default new HYRequest()

使用封装的库

import hyRequest from '../service'

hyRequest.request({
  url: "http://www.httpbin.org/get"
}).then(res=>{
  console.log("res:", res);
})

hyRequest.get({
  url: "http://www.httpbin.org/get",
  params: {
    id: 111
  }
}).then(res=>{
  console.log("res:", res);
})