Unified management of axios configuration and api interface in Nuxt.js

This article is based on Nuxt.js version:2.15.8. It is recommended to use the built-in axios of Nuxt.js, nuxtjs / axios( https://axios.nuxtjs.org/)
Original link: https://www.aerowang.cn/articles/3lwhaw2l

This article records some axios configurations during the development of Nuxt.js project. In addition, it refers to the unified management of api interfaces.

If there are any deficiencies or suggestions, you are welcome to communicate~

Setting environment variables using cross env

Generally, there are different environment configurations for project development, testing and launch. The most common is the BASE_URL of the interface. The API request base address of different environments is different, and it is a little troublesome to manually modify the base URL of axios every time. In some Vue projects I see, different. env files are usually created for different environments, such as. env.development, Then configure the basic path variables, such as vue_app_base_api= https://xxx.com/ .

However, in the nuxt.js project (nuxt versions > 2.12 +), it is officially recommended to use Runtime config properties, including publicRuntimeOptions and privateRuntimeOptions.

1. Install cross env

yarn add cross-env -D
# perhaps
npm install --save-dev cross-env

2. Use

Set the environment variable in the scripts of package.json. The format is to write a cross env first, then configure the environment variable. You can write multiple, and finally write the original command, such as:

 "scripts": {
    "dev": "cross-env BASE_URL=http://localhost:8090 BROWSER_BASE_URL=http://localhost:8090 nuxt",
    "build": "nuxt build",
    "start": "cross-env BASE_URL=http://localhost:8090 BROWSER_BASE_URL=https://abcd.com nuxt start"
  }

In this way, when executing different commands, the BASE_URL obtained in the project is also different.

Note: BROWSER_BASE_URL is a configuration property of @ nuxtjs/axios in nuxt.config.js.

The related nuxt.config.js configuration

export default {  
  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {
    retry: false // By default, failed requests are automatically intercepted and retried 3 times if possible
  },
  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:8090'
  },
  // Client related
  publicRuntimeConfig: {
    axios: {
      browserBaseURL: process.env.BROWSER_BASE_URL // Browser request
    }
  },
  // Server
  privateRuntimeConfig: {
    axios: {
      baseURL: process.env.BASE_URL // Server request
    }
  }
}

Here, you can get the environment variables set through cross env through process.env.

Here, you can set the baseURL in public runtimeoptions and private runtimeoptions. For details, see https://axios.nuxtjs.org/options#runtime-config

  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:8090'
  },

The configuration here is also well understood. If the current environment variable configuration contains a BASE_URL, the current process.env.BASE_URL is the set variable value, otherwise it is the default value ' http://localhost:8090 '

  // Client related
  publicRuntimeConfig: {
    axios: {
      browserBaseURL: process.env.BROWSER_BASE_URL // Browser request
    }
  },
  // Server
  privateRuntimeConfig: {
    axios: {
      baseURL: process.env.BASE_URL // Server request
    }
  }

During isomorphism, the baseURL in the privateRuntimeConfig configuration takes effect only when requested by the server, while the browserBaseURL is the baseURL address when requested by the client.

For example, in the server, the API server listens to port 8090, so on the server side, the nuxt.js program passes the ' http://127.0.0.1:8090 'request API, while the client requests API through https: / / domain name.

In this way, when the server renders, the address of the requested data is the local intranet and the client's request is the extranet address. If this is not set, the intranet may also make API requests through the extranet domain name, which will increase the CDN traffic (if CDN is used).

api interface unified management

Create an api folder under the project root directory to store various interface modules, such as article.js:

export default $axios => ({
  getArticleList () {
    return $axios.$get('/api/posts')
  },
  // Other interfaces
})

The same is true for other interface modules.

Secondly, create a new api.js in the plugins directory and inject it in $root and context. For details, see https://nuxtjs.org/docs/directory-structure/plugins#inject-in-root–context

import articleModule from '../api/article'
export default function ({ $axios }, inject) {
  const apiModules = {}
  $axios.onRequest((config) => {
  	// Related configuration
  })
  apiModules.article = articleModule($axios)
  // Inject to context as $api
  inject('api', apiModules)
}

Finally, don't forget to introduce the plug-in in nuxt.config.js:

export default {
  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    './plugins/api'
  ],
  // Other configurations
}

Use example

In asyncData:

  async asyncData ({ $api }) {
    const { data: articleList } = await $api.article.getArticleList()
    return { articleList }
  },

In methods:

    getArticleList () {
      this.$api.article.getArticleList().then((res) => {
        console.log(res)
      })
    }

Keywords: Front-end Vue.js

Added by hakmir on Tue, 09 Nov 2021 20:22:55 +0200