Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

The project implementation built on NuxtJS 2.x, using @nuxtjs/axios as ^5.3.6

  • NuxtJS website
  • Axios Chinese website

@ nuxtjs/axios features:

  • ✓ Base urls are automatically set on both client and server
  • ✓ Expose setToken function methods on $AXIos objects, and set tokens easily
  • ✓ The withCredentials feature is automatically enabled when requests are sent to the base URL
  • ✓ Useful header information in SSR mode
  • ✓ Fetch style requests
  • ✓ Is perfectly integrated with Nuxt.js Progressbar
  • ✓ Proxy Module is supported
  • ✓ Automatic retry mechanism axios-retry

configuration

Configure it in the nuxt.config.js file

Install @nuxtjs/axios
npm install @nuxtjs/axios --save

// 2. Configure nuxt.config.js
module.exports = {
  plugins: [{ src: "~plugins/axios"}].modules: ["@nuxtjs/axios"].server: {
    port: process.env.PORT || 3000.host: "0.0.0.0",},axios: {
    proxy: true./ / agent
    baseURL: `http://${process.env.HOST || "localhost"}:${
      process.env.PORT || 3000
    }`,}};Copy the code

Axios secondary encapsulation

  1. You can configure basic properties such as baseURL, timeout, withCredentials, and so on
  2. Request interceptor: What do you do before sending a request, such as adding tokens or other public parameters
  3. Response interceptor: What do you do with the response data, such as a unified error message based on the return code defined with the back end
  4. Error processing: According to the status code or other representations, different error messages are returned and processed in a unified manner
/ / plugins/axios. Js file
export default ({ $axios, redirect }) => {
  // Basic configuration
  $axios.defaults.timeout = 10000

  // Request interceptor
  $axios.onRequest((config) = > {
    // console.log('Making request to ' + config.url)
    return config;
  });

  // Response interceptor
  $axios.onResponse((resp) = > {
    return Promise.resolve(resp.data);
  });

  $axios.onError((error) = > {
    const code = parseInt(error.response && error.response.status);
    if (code === 404 || code === 500) {
      redirect("/error");
    }

    return Promise.reject(error);
  });
};
Copy the code

use

export default {
  asyncData({ query, $axios }) {
    $axios.post("xxx", params).then(() = > {});
  },
  mounted() {
    this.$axios.post("xxx", params).then(() = >{}); }};Copy the code