axios

Axios is a Promise-based HTTP library that can be used in browsers and Node.js, and is officially recommended by Vue; Encapsulate AXIOS for future maintenance and custom processing of requests

The installation

npm i axios

encapsulation

I wrapped the AXIos request in HTTP.js and rewrapped the GET request and POST request

First, introduce Axios

import axios from 'axios'
Copy the code

Set the interface request prefix

Generally we will have development, test, production environment, prefix need to distinguish, we use node environment variable to determine.

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = 'http://dev.xxx.com'
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = 'http://prod.xxx.com'
}
Copy the code

When debugging with localhost, using the development address directly usually has cross-domain problems, so we also need to configure the proxy

This project is built by Vue CLI3, and the proxy configuration is in the vue.config.js file:

module.exports = {
  devServer: {
    proxy: {
      '/proxyApi': {
        target: 'http://dev.xxx.com',
        changeOrigin: true,
        pathRewrite: {
          '/proxyApi': ' '
        }
      }
    }
  }
}
Copy the code

This successfully points the /proxyApi to ‘http://dev.xxx.com’ and restarts the service

Modify the configuration in http.js

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '/proxyApi'
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = 'http://prod.xxx.com'
}
Copy the code

The interceptor

Next, set the timeout and request header information

Axios. Defaults. Timeout = 10000 / / request header is set axios for a post request. The defaults. Headers. Post ['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
Copy the code

Axios useful, one of which is its interceptor is very strong, we can set the interceptor for requests and responses, such as request interceptor can add a token in each request, made a unified processing is also convenient to maintain and response the interceptor can do a layer of a response is received after the first operation, such as login status, authorization by its status code.

/ / request interceptor axios. Interceptors. Request. Use (config = > {/ / every time before sending a request to judge whether there is a token / / if it exists, is unified in the HTTP request header and token, Such background according to the token to judge your login, the token is stored after the user logs in to the token in the localstorage && (config. Headers. Authorization = token)return config
  },
  error => {
    returnPromise. The error (error)}) / / response interceptor axios. Interceptors. Response. Use (response = > {/ / if the returned a status code of 200, shows that interface request is successful, Can get data normally // otherwise throw an errorif (response.status === 200) {
    if(Response.data.code === 511) {// Unauthorized call authorization interface}else if(Response.data.code === 510) {// No login to login page}else {
      return Promise.resolve(response)
    }
  } else {
    returnPromise. Reject (response)}}, error => {// We can do unified processing for exception state hereif(error.response.status) {// Handle request failures // Handle different return code pairs accordinglyreturn Promise.reject(error.response)
  }
})

Copy the code

Get POST encapsulation

HttpGet: One argument is the url of the request and one carries the request argument, which returns a Promise object

/ / get requestexport function httpGet({
  url,
  params = {}
}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params
    }).then((res) => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

Copy the code

HttpPost: a transformRequest is processed using a transformRequest, and a data parameter is provided. The other two parameters url,params and GET request the same;

/ / post requestexport function httpPost({
  url,
  data = {},
  params = {}
}) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'post',
      transformRequest: [function (data) {
        let ret = ' '
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        returnThen (res => {resolve(res.data)})})}Copy the code

How to use

I put all the interface calls in the api.js file

The encapsulated method is introduced and then reencapsulated as a method on the interface to be called

import { httpGet, httpPost } from './http'
export const getorglist = (params = {}) => httpGet({ url: 'apps/api/org/list', params })

Copy the code

It can be called in a page like this:

// .vue
import { getorglist } from '@/assets/js/api'

getorglist({ id: 200 }).then(res => {
  console.log(res)
})
Copy the code

In this way, the API can be unified management, maintenance and modification only need to operate in the api.js file.

The complete code

Finally, post the complete code

// http.js
import axios from 'axios'// Environment switchif (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '/proxyApi'
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = 'http://prod.xxx.com'} / / request interceptor axios. Interceptors. Request. Use (config = > {token && (config. Headers. Authorization = token)return config
  },
  error => {
    return Promise.error(error)
  })

axios.defaults.timeout = 10000

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'/ / response interceptor axios. Interceptors. Response. Use (response = > {if (response.status === 200) {
    if(Response.data.code === 511) {// Unauthorized call authorization interface}else if(Response.data.code === 510) {// No login to login page}else {
      return Promise.resolve(response)
    }
  } else {
    returnPromise. Reject (response)}}, error => {// We can do unified processing for exception state hereif(error.response.status) {// Handle request failures // Handle different return code pairs accordinglyreturnPromise.reject(error.response)}}) // Get the requestexport function httpGet({
  url,
  params = {}
}) {
  returnnew Promise((resolve, reject) => { axios.get(url, {params}). Then ((res) = > {resolve (res) data)}). The catch (err = > {reject (err)})})} / / post requestexport function httpPost({
  url,
  data = {},
  params = {}
}) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'post',
      transformRequest: [function (data) {
        let ret = ' '
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        returnThen (res => {resolve(res.data)})})}Copy the code
// api.js
import { httpGet, httpPost } from './http'
export const getorglist = (params = {}) => httpGet({ url: 'apps/api/org/list', params })

export const save = (data) => {
  return httpPost({
    url: 'apps/wechat/api/save_member',
    data
  })
}
Copy the code
// .vue
<script>
import { getorglist } from '@/assets/js/api'
export default {
  name: 'upload-card'.data() {},
  mounted() {
    getorglist({ id: 200 }).then(res => {
      // console.log(res)
    })
  },
}
</script>
Copy the code

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

Updated on March 25

First, thank you for helping me speak. I didn’t expect this article to be read so much. I just took notes and thought that no one would read them

The article has been updated and revised in response to comments in the comments section

The comment section asks why there is an extra layer of wrapping around the promise instead of returning axios directly. Let me make a general statement here:

Return axios.get(). Then (res=>res.data); Resolve (res.data) is more elegant than resolve(res.data). This note also provides an idea for reference only. Partners can choose according to their actual business needs.

This time, I also want to record the use of AXIos. If there are any shortcomings, please give your comments (try to be gentle). I will make adjustments and corrections according to the actual business needs and your opinions in the future (keep updating ~).