1. What is Axios and why unified encapsulation?

Axios is a Promise based HTTP library that runs in both the browser and Node.js. It has many great features, such as unified request and response interception, request cancellation, json conversion, client-side XSRF defense, and more. So the AXIOS library is directly recommended for daily development. If you’re not familiar with Axios, you can refer to the Axios documentation. To get back to the point, the main purpose of the axiOS package and THE UNIFIED management of the API interface is to help simplify the code and facilitate the later maintenance of the update.

2. Encapsulate interceptors and GET/POST requests uniformly

import axios from 'axios'    
import { Loading, Message } from 'element-ui'// Here I am using the elementUI component to import router from the prompt'@/router'

letLoadingInstance = null // Load global loading const instance = axios.create({// Create an axios instance, where you can set the request's default configuration timeout: BaseURL: process.env.node_env ==='production' ? ' ' : '/api'// Set the baeUrl} for different environments according to the reverse proxy you configure. Several types of POST requests are described below'Content-Type'
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

letHttpCode = {// Here is a simple list of common HTTP status code information, you can modify the configuration 400:'Request parameter error',
  401: 'Insufficient permissions, please log in again',
  403: 'Server denied this access',
  404: 'Requested resource not found',
  500: 'Internal server error',
  501: 'Server does not support method used in request',
  502: 'Gateway error',
  504: 'Gateway timed out'} / * * / * * add request interceptor instance. The interceptors. Request. Use (config = > {config. Headers ['token'] = sessionStorage.getItem('token') | |' 'LoadingInstance = loading. service({// The spinner is closed when the request fails or a response is received:'fa fa-spinner fa-spin fa-3x fa-fw',
    text: 'Desperately loading... '
  })
  if (config.method === 'get') {// Add timestamp parameter to prevent browser (IE) from caching get requests config.params = {... config.params, t: New Date().getTime()}} new Date().getTime()}} new Date().getTime()}}if (config.url.includes('pur/contract/export')) {
    config.headers['responseType'] = 'blob'} // I am sending a binary stream, so I need to set the request header'Content-Type'
  if (config.url.includes('pur/contract/upload')) {
    config.headers['Content-Type'] = 'multipart/form-data'
  }
  returnConfig}, error=> {// What to do about the request errorreturnPromise. Reject (error)})/response interceptor * * / * * add instance. Interceptors. Response. Use (response = > {loadingInstance. Close ()if (response.data.status === 'ok') {// The status: OK in the response result is the agreement between me and the background, you can make corresponding judgment according to the actual situationreturn Promise.resolve(response.data)
  } else {
    Message({
      message: response.data.message,
      type: 'error'
    })
    return Promise.reject(response.data.message)
  }
}, error => {
  loadingInstance.close()
  if(error.response) {// According to the request failed HTTP status code to send the corresponding prompt to the userlet tips = error.response.status in httpCode ? httpCode[error.response.status] : error.response.data.message
    Message({
      message: tips,
      type: 'error'
    })
    if(error.response.status === 401) {// Jump to the login page in case of token or login failure. You can perform corresponding actions according to different response results. Router.push ({path: '/login'})} router-push ({path: '/login'})}return Promise.reject(error)
  } else {
    Message({
      message: 'Request timed out, please refresh and try again'.type: 'error'
    })
    return Promise.reject(new Error('Request timed out, please refresh and try again')}}) /* Encapsulates the get request */export const get = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'get', url, params, ... Then (response => {resolve(response)}). Catch (error => {reject(error)})})} /* Encapsulate the POST request */export const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post', url, data, ... Config}).then(response => {resolve(response)}).catch(error => {reject(error)})})} /* Promise.resolve() and promise.reject () return Promise objects, both of which are syntactic sugar */export const post = (url, data, config = {}) => {
  return instance({
    method: 'post', url, data, ... config }).then(response => {return Promise.resolve(response)
  }).catch(error => {
    return Promise.reject(error)
  })Copy the code

Here are some of the arguments to the interceptor’s callback function:

  • Request config in the interceptor



  • Response in the interceptor



  • Response error in interceptor



3. Manage interfaces and apis in a unified manner

// Each module should have its own interface file to manage the unified API import {get, post} from'@/utils/request'

export const query = (params) => get('/pur/pay/pageInit', params)Copy the code

4. Use on the page

import { query } from '@/api/index'

export default {
  name: 'App'.data () {
    return{}},mounted () {
    let params = { userName: 'admin', password: '123456'}
    query(params).then(res => {
      console.log(res, This is the result of the response.)}}}Copy the code

5. Problem sorting

  • How to set different request headers for different interfaces and in what order of priority?

You can config the request interceptor to determine, set separately. You can also use an encapsulated GET/POST request to pass information about config as the third parameter when calling the API. Configuration precedence: The configuration is merged in a precedence order: the library defaults found in lib/defaults.js, then the instance defaults properties, and finally the requested Config parameters. The latter will take precedence over the former.

  • Why encapsulate only GET and POST requests?

Normally axios only needs to encapsulate POST and GET requests, which is the code specification of many companies. Why not use other request methods, such as PUT (upload file to server) and delect (delete), which are relatively unsafe to operate on data directly?

  • Why not introduce the AXIos plugin without vue.use ()

Use (axios) is a plug-in, but you don’t need to use it through vue.use (axios). Once you download it, you just need to introduce it into your project. If you use vue.use (), the install method will be called by default. However, the authors of Axios don’t seem to have a way to write install. The component type imported by Vue must be Function or Object. If it is an object, the install method must be provided, using vue.use (); if it is a function, it will be executed as install directly

  • Describe the common content-type data format for POST requests.

1. Application/JSON: The parameters are placed directly in the request body and sent to the back end in JSON format. This is also the default for axios requests. This type is most widely used.




2. Application/X-www-form-urlencoded: The data in the request body will be sent to the back end as a normal form (key-value pairs).





3. Multipart /form-data parameters will be separated in the request body with label as unit and delimited by a delimiter (custom boundary can be used). You can upload both key-value pairs and files. A format commonly used to upload files.



Finally: my article will be updated and improved… if it is helpful to you, please click “like” ^_^, or leave a comment