preface

I recently built a VUE project myself based on business requirements, interacting with backend data using AXIos. Axios is a Promise-based HTTP library that intercepts and responds to requests, client-side defense against XSRF, etc.

Install axios

npm install axios;
Copy the code

File partition

Create a new API folder under SRC and create an http.js file inside. The http.js file is used to wrap AXIos

http.js
import axios from 'axios'; / / HTTP request interceptor axios. Interceptors. Request. Use (config = > {if(config.method! ='get'){
            config.data = JSON.stringify(config.data);
        }
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; <! -- Set token to check whether you are in login state, and bring token with each request -->let token = window.sessionStorage.getItem("TOKEN");
        if(token){
            config.params = {'token':token}
        }
        return config;
    },
    error =>{
        return Promise.reject(error)
    }
)

Copy the code

Note that when using axios’s POST request to pass data: axios.post(URL,{XXX: XXX}). Then an argument error occurs and the object form is converted to a string key-value pair.

Response interceptor

Response interceptors generally manage status codes and return different operations for different status codes

/ HTTP response interceptor axios. Interceptors. Response. Use (response = > {/ / / / to configure some status codeif(response.data.errCode == 2){

        // }
        returnresponse; }, error =>{// Negotiate configuration with background personnelreturn Promise.reject(error)
    }
)
Copy the code

Encapsulate get, POST methods (put,patch, etc.)

Get request parameter transfer mode and POST request parameter transfer mode.

Get request 1, which can be spelled directly on the URL axios.get('/user? id=111').then(res=>{console.log(res)}).catch(err=>{console.log(err)})'/user',{
    params:{
        id:111
    }
})
.then(res=>{
    console.log(res)
})
.catch(err=>{
    console.log(err)
})
Copy the code
Post request: put arguments directly into an object axios.post('/user'{
    id:111
})
.then(res=>{
    console.log(res)
})
.catch(err=>{
    console.log(err)
})
Copy the code

Subject to the

* Encapsulate get methods * @param URL * @param params * @returns {Promise} */export function get(url,params={}){
     returnnew Promise((resolve,reject)=>{ axios.get(url,{ params:params }) .then(res=>{ resolve(res.data) }) .catch(err=>{ Reject (err)})})} /** * Encapsulates the POST request * @param URL * @param params * @returns {Promise} */export function post(url,params = {}){
     return new Promise((resolve,reject)=>{
         axios.post(url,params)
         .then(res=>{
            resolve(res.data)
         })
         .catch(err=>{
            reject(err)
         })
     })
 }
Copy the code

Introduced in main.js

import axios from 'axios'
import {get,post} from './api/http'// Define the global variable vue.prototype.$get = get;
Vue.prototype.$post = post;
Copy the code

Used in components

let param={}
this.$get('queryParam',param). Then (res=>{console.log(res)}) PostCopy the code

Extensions (these are some of the subsequent extensions)

Environment configuration

The project environment will have three environments: development, test and production. The default interface URL prefix can be matched using node’s environment variables. (ACTUALLY I don’t understand why??) You can set the default request address for AXIos via axios.defaults.baseURL.

// Environment switchif (process.env.NODE_ENV == 'development') {
	axios.defaults.baseURL = 'https://www.baidu.com'; }else if (process.env.NODE_ENV == 'debug') {
	axios.defaults.baseURL = 'https://www.ceshi.com';
}
else if (process.env.NODE_ENV == 'production') {
	axios.defaults.baseURL = 'https://www.production.com';
}
Copy the code

Setting request Timeout

axios.default.timeout = 10000;
Copy the code