The reason

I’ve been writing small projects that have fewer axiOS requests, most of which are separate AXIOS requests for a few pages and therefore have never been wrapped by AXIOS.

After joining the company, I found that there were too many requests, so I needed to encapsulate AXIos. Here is what I learned.

Code to learn

structure

In LIBS, encapsulation is the main method

XHR. Js axios encapsulation

import axios from 'axios'

// Create an instance
const request = axios.create({
  baseURL: ' '
})

//buildUri handles url methods

function xhr(option) {
    const uri = buildUri(options)
    const reqConfig = {
        method: options.method,
        url: uri,
        headers: {}}if (options.headers) {
        Object.keys(options.headers).forEach(header= > {
          reqConfig.headers[header] = options.headers[header]
        })
     }
     // Add attributes to reqConfig such as request headers, params, etc
     // ...
     return request(reqConfig) / / output
}

export default xhr / / export

Copy the code

The first encapsulation is complete

Request.js requests AXIos encapsulation

The second wrapper imports common ununit.js wrapper methods

//request.js
const API = {
  assets: util.getAPI('assets'),
  scenes: util.getAPI('scenes'),
  maps:util.getAPI('maps'),
  styles: util.getAPI('styles'),
  tilesets: util.getAPI('tilesets'),
  sprites: util.getAPI('sprites'),
  models: util.getAPI('models'),
  tables: util.getAPI('tables'),
  databases: util.getAPI('databases'),
  catalogs: util.getAPI('catalogs')}/ / output
export const getJSON = url= >
  xhr({
    method: 'GET'.uri: url
  })
  
//config.js defines the runtime environment
export default {
  API: window.config.API_URL,
  TITLE: window.config.TITLE,
  PUBLIC_COUNT: 'admin'
}
//unit.js
getAPI(module) {
    return `${config.API}/The ${module}/v1`
  }
Copy the code

Use after encapsulation

// Take getJSON as an example

/ / introduction
import { getJSON } from '@/libs/request'
/ / use
let { data } = await getJSON(source.url)
Copy the code

Store data as objects

Define the config. Js

export default {
  API: window.config.API_URL,
  TITLE: window.config.TITLE,
  PUBLIC_COUNT: 'admin'
}
Copy the code

When you introduce it directly

import config from 'config.js'
Copy the code