二次封装axios

什么是axios

Axios 是一个基于 promise 的 HTTP 库,它的底层是基于 ajax进行封装。

不封装使用方式

// 执行get请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//也可以使用下面这种方式携带参数
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//执行post请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

为什么需要对axios进行封装

对api进行统一管理,方便后期代码的维护。

如何封装

在项目的src目录下新建utils文件夹,在该文件夹下新建request.js文件。

import axios from 'axios'

const  http = axios.create({
    baseURL:'/api',     //通用请求的地址前缀
    timeout:10000       //超时时间
})

//添加请求拦截器
http.interceptors.request.use(function(config){
    //在发送请求之前做些什么
    return config;
},function(error){
    //对请求错误做些什么
    return Promise.reject(error);
})

//添加响应拦截器
http.interceptors.response.use(function(response){
    //对响应数据做点什么
    return response
},function(error){
    //对响应错误做点什么
    return Promise.reject(error)
})

export default http

猜你喜欢

转载自blog.csdn.net/weixin_51382988/article/details/128306845