preface

When doing large projects in VUE, axios is officially recommended, but native AXIos may not be suitable for the project, so encapsulate AXIos at the beginning of the project to maintain the consistency of data processing throughout the project. This article focuses on how to encapsulate AXIOS, encapsulate requests, encapsulate common apis, and how pages invoke requests in vue-CLI projects.

Formal configuration route: 1. To get the project and background interface, the first thing to do is to configure the global agent and the second point. 2. Globally encapsulate AXIos and request.js. 3. Filter axiOS request mode, control path and parameter format and the fourth point http.js. 4. Formally encapsulate API and fifth point api.js. 5. Page invocation.Copy the code

The body of the

I. Preliminary configuration of VUE project

Create a new Vue project, download Axios, and import Axios in main.js.

npm i axios -S
Copy the code
// main.js
import axios from "axios"
Copy the code

2. Configure the proxy address in the Config file

The index.js file in the project config directory is mainly used to configure multiple background interfaces.

Vue cil2 old version of the proxy configuration -confin/index.js

 dev: {
    // Paths
    assetsSubDirectory: 'static'.assetsPublicPath: '/'.// The back end requests the address proxy, and when invoking the page of testIp, it can directly refer to http://197.82.15.15:8088
    proxyTable: {
      '/testIp': {
        target: 'http://197.82.15.15:8088'.changeOrigin: true.pathRewrite: { 
          '^/testIp': ' '}},'/elseIp': {
        target: 'http://182.83.19.15:8080'.changeOrigin: true.pathRewrite: { 
          '^/esleIp': ' '}}},// Various Dev Server settings
    host: 'localhost'.// can be overwritten by process.env.HOST
    port: 8080.// can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false.errorOverlay: true.notifyOnErrors: true.poll: false.// https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-


    /** * Source Maps */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map'.// If you have problems debugging vue files in devTools,
    // Set this to false, it may be helpful
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true.cssSourceMap: true
  },


Copy the code

Vue cil 3+ The new version of the agent configuration vue.config.js file

About multi-agent configuration:

		 devServer: {
            overlay: { // Make the browser overlay display both warnings and errors
              warnings: true.errors: true
            },
            host: "localhost".port: 8080./ / the port number
            https: false.// https:{type:Boolean}
            open: false.// Automatically start the browser after configuration
            hotOnly: true./ / hot update
            // proxy: 'http://localhost:8080' // Configure cross-domain processing with only one proxy
            proxy: { // Configure multiple agents
                "/testIp": {
                    target: "http://197.0.0.1:8088".changeOrigin: true.ws: true./ / the websocket support
                    secure: false.pathRewrite: {
                        "^/testIp": "/"}},"/elseIp": {
                    target: "http://197.0.0.2:8088".changeOrigin: true./ / ws: true, / / the websocket support
                    secure: false.pathRewrite: {
                        "^/elseIp": "/"}}}},Copy the code

Wrap an axios instance — Request.js

Create a new utils folder in the project SRC directory, and then create request.js, which will write the wrapper process of AXIos.

/**** request.js ****/
/ / import axios
import axios from 'axios'
// Use element-ui Message as a Message reminder
import { Message} from 'element-ui';
//1. Create a new axios instance
const service = axios.create({
  // Public interface -- note this later
  baseURL: process.env.BASE_API,
  // The unit of the timeout period is ms, where the timeout period is 3s
  timeout: 3 * 1000
})
// 2. Request interceptor
service.interceptors.request.use(config= > {
  // Do some processing before sending a request, such as data conversion, request header configuration, token setting, loading setting, etc
   config.data = JSON.stringify(config.data); // Data conversion, also can use QS conversion
   config.headers = {
     'Content-Type':'application/x-www-form-urlencoded' // Configure the request header
   }
   // Note that the cookie method or the local localStorage method should be introduced when using the token. Js-cookie is recommended
   const token = getCookie('name');// Before you can get your token, you must get your token and deposit it
   if(token){
      config.params = {'token':token} // If required to carry in the parameters
      config.headers.token= token; // If the request is carried in the request header
    }
  return config
}, error= > {
  Promise.reject(error)
})

// 3. Response interceptor
service.interceptors.response.use(response= > {
  // Some common processing after receiving the response data and succeeding, such as closing loading, etc
  
  return response
}, error= > {
   /***** The processing of abnormal responses is started *****/
  if (error && error.response) {
    Public error handling
    // 2. Process according to the response code
    switch (error.response.status) {
      case 400:
        error.message = 'Error request'
        break;
      case 401:
        error.message = 'Not authorized, please log in again'
        break;
      case 403:
        error.message = 'Access denied'
        break;
      case 404:
        error.message = 'Request error, resource not found'
        window.location.href = "/NotFound"
        break;
      case 405:
        error.message = 'Requested method not allowed'
        break;
      case 408:
        error.message = 'Request timed out'
        break;
      case 500:
        error.message = 'Server side error'
        break;
      case 501:
        error.message = 'Network not implemented'
        break;
      case 502:
        error.message = 'Network error'
        break;
      case 503:
        error.message = 'Service unavailable'
        break;
      case 504:
        error.message = 'Network timeout'
        break;
      case 505:
        error.message = 'The HTTP version does not support this request'
        break;
      default:
        error.message = 'Connection error${error.response.status}`}}else {
    // Timeout processing
    if (JSON.stringify(error).includes('timeout')) {
      Message.error('Server response timed out, please refresh current page')
    }
    error.message = 'Failed to connect to server'
  }

  Message.error(error.message)
  /***** No further action is required *****/
  // If no error handling is required, the above processing can be omitted
  return Promise.resolve(error.response)
})
//4. Import the file
export default service

Copy the code

Special note:

As for the data conversion, here is a special explanation

config.data = JSON.stringify(config.data);
config.headers = { 'Content-Type':'application/x-www-form-urlencoded'  }
const token = getCookie('name')
if(token){ 
  config.params = {'token':token} ; 
  config.headers.token= token; 
}

Copy the code
  • The above code is required as a configuration item of the request, and is optional and situational.data/headers/paramsThis kind of parameters have a variety of itself, and background communication, what you need to match what!
  • config.data = JSON.stringify(config.data)Why not?qs.stringify“, because all my background wants is json pass-throughs, whereas QS converts to key-value pair concatenation strings. Of course you need to pass string parameters in the background, so convert to QS or whatever.
  • Const token = getCookie(name)This is the value of the token, you must send a request to get the token before taking it, and then the sheCookie saves it, and the name is the name of the token you saved, everyone’s name is different.
  • config.headers = {'Content-Type':'application/x-www-form-urlendoded'}The configuration of the request header content is also different,application/x-www-form-urlendodedThe :form data is encoded and sent to the server in key/value format (the default form submission format). You can configure it as required.
  • If, after the final configuration is complete, an error message fails to connect to the server, that is normal, because the server address configured in the example is a fake address that needs to be replaced with your own server.

4. Encapsulate the request — http.js

Create a new http.js file in the utils folder of the project SRC directory. This file is used to encapsulate several requests.

/**** http.js ****/
// Import the wrapped AXIos instance
import request from './request'

const http ={
    /** * methods: Request methods * URL request address * params request parameter */
    get(url,params){
        const config = {
            method: 'get'.url:url
        }
        if(params) config.params = params
        return request(config)
    },
    post(url,params){
        const config = {
            method: 'post'.url:url
        }
        if(params) config.data = params
        return request(config)
    },
    put(url,params){
        const config = {
            method: 'put'.url:url
        }
        if(params) config.params = params
        return request(config)
    },
    delete(url,params){
        const config = {
            method: 'delete'.url:url
        }
        if(params) config.params = params
        return request(config)
    }
}
/ / export
export default http

Copy the code

Formally encapsulate the API for sending requests — api.js

Create a new API folder in the project SRC directory, and then create api.js. This file is the wrapper that writes the API.

Writing method 1, suitable for classification and export:

import http from '.. /utils/http'
// 
/ * * * resquest request address For example: http://197.82.15.15:8088/request/... * '/testIp' represents the proxy */ configured in vue-cil config, index.js
let resquest = "/testIp/request/"

/ / get request
export function getListAPI(params){
    return http.get(`${resquest}/getList.json`,params)
}
/ / post request
export function postFormAPI(params){
    return http.post(`${resquest}/postForm.json`,params)
}
/ / put request
export function putSomeAPI(params){
    return http.put(`${resquest}/putSome.json`,params)
}
/ / delete request
export function deleteListAPI(params){
    return http.delete(`${resquest}/deleteList.json`,params)
}


Copy the code

Writing method 2, suitable for all export:

import http from '.. /utils/http'
// 
/ * * * resquest request address For example: http://197.82.15.15:8088/request/... * '/testIp' represents the proxy */ configured in vue-cil config, index.js
let resquest = "/testIp/request/"

/ / get request
export default{
 	getListAPI(params){
    	return http.get(`${resquest}/getList.json`,params)
	},
	 postFormAPI(params){
    	return http.post(`${resquest}/postForm.json`,params)
	}
}

Copy the code

Note: in a project, if the background request is not the same IP, but multiple IP, can create multiple JS under the API folder, used to call the request.

Let’s take a look at one of the remaining questions:

// Create a new axios instance
const service = axios.create({
    baseURL:process.nev.BASE_API,
    timeout:3 * 1000
})
Copy the code

The global variable process.env.base_api in Webpack was used to encapsulate the baseUrl of the public interface, rather than write the IP directly. This is also to accommodate multiple background or development API addresses that are different from the published API addresses.

The above configuration environment and interface is basically set up, let’s look at the call

How to call in vUE file

Method one:

Call whichever API is used – this applies to the interface classification export above.

 import {getListAPI,postFormAPI, putSomeAPI, deleteListAPI} from '@/api/api'

  methods: {
      // Promise calls, chained calls, getList() only accepts arguments in parentheses;
      // get does not pass the parameter
      getList() {
        getListAPI().then(res= > console.log(res)).catch(err= > console.log(err))
      },
        / / post to participate
      postForm(formData) {
        let data = formData
        postFormAPI(data).then(res= > console.log(res)).catch(err= > console.log(err))
      },

      //async await synchronous call
      async postForm(formData) {
        const postRes = await postFormAPI(formData)
        const putRes = await putSomeAPI({data: 'putTest'})
        const deleteRes = await deleteListAPI(formData.name)
        // Data processing
        console.log(postRes);
        console.log(putRes);
        console.log(deleteRes); }},Copy the code

Method 2:

Import all the apis, and then use whichever API to call — applies to all exports

   import api from '@/api/api'
   methods: {
     getList() {
        api.getListAPI(data).then(res= > {
          // Data processing
        }).catch(err= > console.log(err))
      }
    }  

Copy the code

conclusion

Above, is introduced in detail in the vue – cil project how to encapsulate axios, packaging request, encapsulate the public API, configure multiple interfaces, such problems as how to invoke the request page, is a useful ~ kiss measuring, but the packaging method is more suitable for large projects, the configuration is reasonable, if it is their own small project, it is ok to use axios directly.