HTTP module overall directory structure

The SRC folder | | - HTTP encapsulation axios module -- config. The default configuration of js axios -- API. Js secondary packaging axios, Error, authentication, jump, intercept, tips, etc -- index. Js axios encapsulated into plug-in - modules request interface file directory | -- index. Js automation processing files: Automatic import the core file of the interface ---- home.js interface 1 ---- news.js interface 2Copy the code

1. Config information –config.js

import {
  baseUrl
} from '.. /config/urls.js'/** * Default configuration */exportBaseURL: baseURL, headers: {'Content-Type': 'application/json; charset=UTF-8'.'Accept': 'application/json'}, // set the timeout time to timeout: 10000, // withCredentials // withCredentials:false// return data type responseType:'json',}Copy the code

2. API module –api.js

import axios from 'axios'// Import qs from'qs'// Serialize the request data, depending on the server's requirements import config from'./config.js'Import the default configuration import store from'@/store/'

letcancel, promiseArr = {} const CancelToken = axios.CancelToken; __axiosPromiseArr = []; Const instance = axios. Create (config) / / request interceptor instance. The interceptors. Request. Use request (= > {/ / * * * * * * * * 1, initiate the request, Cancel the same request currently in progress ************if (promiseArr[request.url]) {
      promiseArr[request.url]('Operation cancel')
      promiseArr[request.url] = cancel
    } else{promiseArr[request.url] = cancel} //******** *********** // Tip: 1 // At the beginning of the request, you can use vuex to enable full-screen loading animation store.com MIT ('SET_LOADING'.true); // With a token, you can combine vuex or weightlocalStorage
    // if (store.getters.token) {
    // request.headers['X-Token'] = getToken() // Let each request carry token--['X-Token'] For a user-defined key, change the key as required. //}else{// // redirect to login page //} // Tip: 3 // According to the request method, serialize the incoming parameters, according to the back-end requirementsif (request.method.toLocaleLowerCase() === 'post' ||
      request.method.toLocaleLowerCase() === 'put' ||
      request.method.toLocaleLowerCase() === 'delete') {

      request.data = qs.stringify(request.data)
    }
    return request
  },
  error => {
    console.log('request:'// Tip: 4 // Close loAdding store.mit ()'SET_LOADING'.false); // 1. Determine that the request timed outif (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
      console.log('The request has timed out based on the timeout you set/the actual request has timed out, you can add a timeout solution here') / /returnservice.request(originalRequest); } // 2. Need to be redirected to the error page const errorInfo = error.response console.log(errorInfo)if(errorInfo) {// error = errorinfo. data// See promise. reject const errorStatus = errorInfo.status; // 404 403 500... Such as the router. Push ({path: ` / error /${errorStatus}`})}returnPromise. Reject (error) / / in the other side of the call can get (catch) what do you want to return the error message}) / / response response interceptor instance. The interceptors. Response. Use (the response => {// Add the timer mainly to show the Loading effect of the project should be removedsetTimeout(() => {
      store.commit('SET_LOADING'.false); }, 300).letdata; / / ie 9 when the response data is undefined, so you need to use the response. The request. The responseText (string) after Stringifyif (response.data == undefined) {
      data = response.request.responseText
    } else{data = response.data} // Depending on the code value returned to do different processing (and back-end convention) // switch (data.code) {//case ' ': / /break; // default: } // if the code is not returned correctly, and the login is complete, // const err = new Error(data.description) // err.data = data // err.response = response // throw errreturn data
  },
  err => {

    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = 'Request error'
          break

        case 401:
          err.message = 'Not authorized, please log in'
          break

        case 403:
          err.message = 'Access denied'
          break

        case404: err.message = 'Error requesting address:${err.response.config.url}`
          break

        case 408:
          err.message = 'Request timed out'
          break

        case 500:
          err.message = 'Server internal error'
          break

        case 501:
          err.message = 'Service not implemented'
          break

        case 502:
          err.message = 'Gateway error'
          break

        case 503:
          err.message = 'Service unavailable'
          break

        case 504:
          err.message = 'Gateway timed out'
          break

        case 505:
          err.message = 'HTTP version not supported '
          break

        default:
      }
    }
    store.commit('SET_LOADING'.false); // Do something about the response error console.error(err) // Here I'm using element UI's prompt component // message. error(' error:${err}`);
    returnPromise.reject(err) // Return error message returned by interface})export default (url = ' ', data = {}, type = 'GET') = > {letoptions = { url, cancelToken: New CancelToken(c => {cancel = c window.__axiospromisarr.push ({cancel}) // Put into a global array for later CancelToken on the router})}type = type.toUpperCase();
  return new Promise((resolve, reject) => {
    if (type= = ='GET') {
      options = Object.assign(options, {
        method: 'get',
        params: data,
      })
    } else if (type= = ='POST') {
      options = Object.assign(options, {
        method: 'post',
        data,
      })
    }
    instance(options)
      .then(res => {
        resolve(res)
        return false})})}Copy the code

Business module –modules

Take the news.js module as an example:

import axios from '.. /api'/ / import APIexport const News = (language = '1'.type = '1') => axios('/news/index', {
    p: 'wx',
    language,
    type});Copy the code

Service module export (key part) :

Under the modules of the index. Js

/** */ const merge = require('webpack-merge')
const files = require.context('. '.true, /\.js$/)

let configInterface;
/**
 * merge interface
 */
 
console.log(files.keys()) // ["./news.js"] returns an array files.keys().foreach (key => {if (key === './index.js') return; const filesConfig = files(key) configInterface = merge({}, configInterface, FilesConfig. Default | | filesConfig) / / read out the default file module})export default configInterface
Copy the code

/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

There’s a very important function here –>require.context

/** * @param directory The directory to search cannot be a variable, Otherwise, at compile time, directories cannot be located * @param useSubdirectories whether to search for subdirectories * @param regExp matches the regular expression of the file, which type of file it matches * @return functionResolve () returns the resolve, keys, and ID of the module after the request was resolved. Keys () returns an array of all the requests that the module in context handled. Id is the module ID contained in the context module. It may be used when you use module.hot.accept */ require.context('demo', useSubdirectories = false, regExp = /\.js$/) // a context containing all files under the demo folder (excluding subdirectories) whose names end in 'js' that can be requested by require.Copy the code

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /

4. Export to Vue instance for global call –index.js

/** * import all interfaces */ import apiList from'./modules/index'   

const install = Vue => {
  if (install.installed) return;
  install.installed = true; Object.defineproperties (vue. prototype, {// here mounted on the Vue prototype$apiOn the object$api: {
      get() {
        return apiList
      }
    }
  })
}
export default install
Copy the code

5, the main js

// Import the index.js import API from the HTTP folder'./http'
Vue.use(api)
Copy the code

Call in component:

this.$api.News().then((res) => {
      console.log(res)
})
Copy the code