The introduction of

Create the resource directory in the SRC directory and create the api.js file to wrap axios

import axios from 'axios';
import qs from 'qs'; // To serialize data of type POSTCopy the code

Runtime environment

- axios.defaults.baseURL = `${window.location.origin}/api/pc/`
Copy the code
  • BaseURl In the case of urls that are relative paths, the URL will be concatenated in baseURl so the AXIos instance can avoid repeating the baseURl part first. Window.location. origin gets the current environment (the URL before the ‘/’). The current environment can be local, test,demo, or official so that the corresponding baseURL can be dynamically matched
  • / API/PC is a match. The local request interface requires the proxy to forward requests. The file to be configured can be found in config/index.js
dev:{
    proxyTable: { '/api/pc': 'sanzhimengxin.com.cn'}}Copy the code

Dev represents the development environment, and proxy options (multiple options can be set in the proxyTable). When the path ‘/ API/PC ‘is matched, the proxy to the corresponding address realizes the cross-domain request.

Set the common configuration (post request method as an example in this article)

axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded; charset=UTF-8'
axios.defaults.timeout = 50000
Copy the code
  • The current request mode is POST, and the request header needs to adopt the Application/X-www-form-urlencoded format
  • Set the request timeout period to 5s

Define callApi methods

const callApi = ({
  api,
  param,
  readonly = true,
  axiosOptions = {},
  error = 'Failed to call interface',
  success = ' ',
  async = false,
  mock = false= > {})if (mock) {
    axiosOptions = Object.assign(axiosOptions, {
      baseURL: 'https://easy-mock.com/mock/5bc94237364160152beb30e7/'}}})Copy the code

The API and baseURL form the complete URL, param is the request parameter, and param is the request parameter. Readonly Specifies whether the interface is read-only (set to true for query and false for save), and whether the parameters can be set to default values. If the last four parameters are set to default values, Mock indicates whether mock data is turned on. If the mock is passed in true, reset baseURL and merge option into the configuration object axiosOptions for later generation of axiOS instances

const callApi = ({
  api,
  param,
  readonly = true,
  axiosOptions = {},
  error = 'Failed to call interface',
  success = ' ',
  async = false,
  mock = false= > {})if (mock) {
    axiosOptions = Object.assign(axiosOptions, {
      baseURL: 'https://easy-mock.com/mock/5bc94237364160152beb30e7/'
    })
  }
  const axiosInstance = axios.create(axiosOptions)
  const params = qs.stringify({
    apiparams: JSON.stringify({ params: param, readonly, async })
  })
}
Copy the code
  • Axios.create generates oneAxios instanceIn this case axiosOptions is that object. The only difference is whether it is mock data. In the case of mock data,Modify the baseURL. The axios.defaults property will still exist if it is set laterSame propertyIt just covers it.
  • (readonly, async)Default values are set, and can also be modified by passing in values. And through theAssemble into Params objectsAs an input parameter carried with the request. Post requests require qs to sequence the input parameter. What is the sequence number that we can compare before and after the input parameter by serializing it

    Before the input parameter is serialized:


Axios is a Promise based HTTP library that runs in browsers and Node.js,

  • So axiosReturn after requestThe promise is followed by the promiseThen and catch methodsAll of them are returnedNew Promise instance, so you can always do chain operations.
const callApi = ({
  api,
  param,
  readonly = true,
  axiosOptions = {},
  error = 'Failed to call interface',
  success = ' ',
  async = false,
  mock = false= > {})if (mock) {
    axiosOptions = Object.assign(axiosOptions, {
      baseURL: 'https://easy-mock.com/mock/5bc94237364160152beb30e7/'
    })
  }
  const axiosInstance = axios.create(axiosOptions)
  const params = qs.stringify({
    apiparams: JSON.stringify({ params: param, readonly, async })
  })
  return axiosInstance
    .post(api, params)
    .then(({ data: { ret: { code, msg }, data } }) => {
      if(code ! = ='200') {
        const message = { code, message: msg || error }
        return Promise.reject(message)
      }
      return data
    })
    .catch(error => {
      console.log(`
        ${'*'.repeat(24)}  api = ${api}  ${'*'.repeat(24)}
        params = ${JSON.stringify(param, null, 2)}
        code = ${error.code}
        errorMessage = ${error.message}
        ${'#'.repeat(70)}
      `)
      return Promise.reject(error)
    })
}
Copy the code
  • Used in the input parameter of the THEN function of the AXIos instanceStructure assignmentTo get the result of the returned value into (much less straightforward. Action) checks if the code returned is 200, if not ‘200’ is usedPromise.reject throws an error, you canBy the catch methodPick up on the misinformation coming out.
  • axios (Request failed or error in then function)In the catch method of an Axios instance, an error message is received and displayed in the print platform, also usedPromise. Reject methodThrow an error, which can be caught by a catch
  • If ‘*’ is used in console.log, the * is printed 24 times. Repeat (24) displays the entry parameters, status codes, and error messages.Easy to view and debugTo avoid manual printing each time.

mount

Axios is wrapped, but it’s too cumbersome to import this file every time we use it. It would be much easier if we mounted the Vue prototype so that we could access the method via this call.

import Vue from 'vue'
import callApi from './resource/api.js'
Vue.prototype.$callApi = callApi
Copy the code
// callApi method this.$callApi({
    api: 'get_first_data',
    param: {
      campusid: 100,
      gradeCode: 1152
    },
    mock: true
}).then(fn)
  .catch(fn)
Copy the code

reference

axios