About axios detailed explanation and secondary packaging

Write custom directory title here

About Axios

What is Axios?

Axios is a promise-based network request library for node.js and the browser. It is isomorphic (ie the same code can run in the browser and node.js). On the server side it uses the native node.js http module, and on the client side (browser side) it uses XMLHttpRequests.
Document address : https://www.axios-http.cn/docs/intro

characteristic

  • Create XMLHttpRequests from the browser
  • Create http request from node.js
  • Support Promise API
  • Intercept requests and responses
  • Transform request and response data
  • cancel request
  • Automatically convert JSON data
  • Client supports defense against XSRF

Install
using npm or other (yarn) etc.

	$ npm install axios

Axios secondary packaging

reason:

    1. There is no need to rewrite some repetitive ones every time a request is made, reducing the amount of code and reducing the difficulty of maintenance.
    1. Unified processing of some common problems, such as: http error.
    1. Intercept requests and responses, and process data in advance, such as obtaining tokens and modifying configuration items. The response is an error handling reminder

// 导入axios
import axios from 'axios'

// 利用axios对象的create方法,去创建一个axios实例
const api = axios.create({
    
    
    baseURL: process.env.VUE_APP_BASE_URL, // 地址(可以根据不地址配置)
    timeout: 5000, // 请求超时时间,提示用户请求超时
    // withCredentials: true //  // `withCredentials` 表示跨域请求时是否需要使用凭证,默认false
})
/**
 * 设置请求数据参数传递的格式,默认是json格式
 * 看服务器要求什么格式,设置一个默认常用的,后请求里还可以修改覆盖
 */
api.defaults.headers['Content-Type'] = 'application/json'

// interceptors 是 axios 的拦截器:在请求或者响应被then或者catch处理前拦截
/**
 * 添加请求拦截
 *     -- 发起请求前做的事情
 */
api.interceptors.request.use(function (config) {
    
    
    // 发送请求前做些什么(添加token、cookie之类的)
    // let token=localStorage.getItem('token')
    // token && (config.headers.Authoriztion=token)
    return config;
}, function (err) {
    
    
    // 做错误处理
    return Promise.reject(err)
})
/**
 * 添加响应拦截
 * 服务器端返回信息->[响应拦截器]->客户端js获取到信息
 * response中包含属性:
 * data:相应数据,status:响应状态码, statusText:响应状态信息,
 *       headers:响应头, config:响应提供的配置信息, request
*/
api.interceptors.response.use(function (res) {
    
    
    // 2xx 范围内的状态码都会触发该函数(这里做响应成功后处理)
    return res.data;//将主体内容返回  axios.get().then(result=>{拿到的就是响应主体});
}, function (err) {
    
    
    // 超出2xx 范围的状态码触发该函数(做错误处理)
    // 如果有返回结果
    if (err) {
    
    
        switch (err.status) {
    
    
            //这里面根据公司需求进行写
            case 404:
                //进行错误跳转之类
                break;
            case 501:
                //进行提示之类的弹窗
                break;
            case 502:
                //进行提示之类的弹窗
                break;
        }
    } else {
    
    
        //服务器没有返回结果 分两种情况 断网  服务器崩了
        if (!window.navigator.onLine) {
    
    
            //断网处理:跳转到断网页面
            return
        }
        return Promise.reject(err)
    }
})

Guess you like

Origin blog.csdn.net/weixin_44897255/article/details/129090304