Axios is one of the most frequently used libraries in front-end development. It runs in a browser and can be used in node.js back-end projects. This article takes a look at some common uses of AXIOS in browsers based on my own development projects.

Basic usage

During project development, you can create an instance through axios.create, and do some configuration to that instance, resulting in an Ajax function specifically designed to communicate with the back-end server.

const instance = axios.create()Copy the code

Here are some configurations for this instance:

baseURL

In a formal or development environment, configuring baseURL makes it easy to set up routing forwarding rules.

const instance = axios.create({
    baseURL: '/api/'
})Copy the code

header

In a single web application, by putting some information in the request header, such as the token at the request header.

// Continue to configure the example you just created
instance.defaults.headers.common['x-auth-token'] = 'some token'Copy the code

interceptors

Interceptors are configured to handle requests and responses. Suppose the server returns something like this:

{
    code: 200.data: Object.msg: ' '
}Copy the code

Where data is the information we really need, add a response interceptor to process and extract data. Check the code value to determine whether the response value meets the requirements. If not, only an error message is returned and the error is handled later in the callback function.

// The response was processed successfully
// Axios wraps the result of the response and fetches data directly
instance.interceptors.response.use(({data}) = > {
    if (data.code === 200) {
        return data.data
    } else {
        console.error(res)
        // Suppose there is a Toast component
        Toast(res.msg)
        return Promise.reject({
            msg: msg
        })
    }
})Copy the code

The use of the params

Sometimes it is easiest to call up an interface that has a lot of query criteria and pass in an object containing the parmas field when using axios.get.

let params = {
    keyWord: null.name: 'xxx'.age: 22
}
// Attributes that are null are filtered out. The final request URL is /person? name=xxx&age=22
instance.get('/person', { params })Copy the code

Upload files to the seven cow example

Instance is used to communicate with the server. Now upload the file to Seven Cows and use Axios directly to upload. According to the Qiniu developer documentation, submit a FormData object to the Qiniu server. The FormData object must contain tokens and files.


const file = document.getElementById('input').files[0]
const formData = new FormData()
formData.append('token', token) // The token is generated on the server side
formData.append('file', file)
axios.post('http://upload.qiniu.com/', formData).then(({ data }) = > {
    console.log(data) / / the return value
})Copy the code

Uploading a file takes a long time. You can listen to the progress event to obtain information about the upload progress. The code for uploading files needs some tweaking.

axios.post('http://upload.qiniu.com/', {
    data: formData,
    onUploadProgress: (e) = > {
        const percentComplete = e.loaded / e.total // Upload progress
    }
}).then(({ data }) = > {
    console.log(data) / / the return value
})Copy the code

In some scenarios, you need to upload the Base64 encoding diagram. According to the qiniu upload document, the content-Type and Authorization of the request header are set during the upload, and base64 encoded images are put into the package body of the request. The code here needs to make some adjustments.

axios({
  method: 'post'.url: 'https://upload.qiniup.com/putb64/-1'.headers: {
    'Content-Type': 'application/octet-stream'.Authorization: `UpToken ${token}`
  },
  data: imgSrc.split('base64,') [1] // Pass content directly
})Copy the code

Used in conjunction with the status management library

In a single web application, the user’s token information is stored in the Store. Some parameters of the AXIOS instance need to be changed dynamically when the user logs in or detects that the token has expired. Suppose the state management library we use here is Redux. In the interceptor, determine whether the token is expired.

instance.interceptors.response.use(({data}) = > {
    if (data.code === 200) {
        return data.data
    } else if (data.code === 40001) {// code: 40001 Indicates that the token expires
      store.commit(CLEAR_TOKEN)
    }
    ...
})Copy the code

When the store changes, the token information passed to the back end is dynamically changed.

store.subscrible((a)= > {
    instance.defaults.headers.common['token'] = store.getState().token
})Copy the code

Work with Vue

In the project, a number of components are imported into the AXIOS library. If the project uses Vue, register the AXIOS instance as a Vue plug-in to avoid the re-import problem. Register the Vue plug-in by adding the Vue instance method.

// http.js creates instance
// Export an object containing the install function
export default {
  install (Vue) {
    Vue.prototype.$http = instance
  }
}
// main.js
Vue.use(http) // In the Vue component this.$HTTP can initiate a requestCopy the code