How to set Nuxt.js' config for axios baseURL to work globally?

Viewed 1847

Created a project via

npm init nuxt-app <project-name>

Config baseURL for axios by here

npm install @nuxtjs/axios

nuxt.config.js

  modules: [
    '@nuxtjs/axios',
  ],

  axios: {
    baseURL: 'http://localhost:9000',
  },

  publicRuntimeConfig: {
    axios: {
      browserBaseURL: process.env.BROWSER_BASE_URL
    }
  },

  privateRuntimeConfig: {
    axios: {
      baseURL: process.env.BASE_URL
    }
  },

Use it in pages/post.vue

axios.get('/posts')

Can't call server in 9000, but got base URL as 3000 which port nuxt.js is running.

If config axios.defaults.baseURL = 'http://localhost:9000' in pages/post.vue, it can access correctly.

2 Answers

Because you are accessing the "global" instance of axios, in order to use the instance provided/configured by @nuxtjs/axios, use this.$axios.get('/posts') in your Vue component.

Check more details here: https://axios.nuxtjs.org/usage

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

UPDATE

To add basic auth with your request, you can extend the $axios instance with nuxt plugin (some details here Extending Axios and here Nuxt Plugin).

Inside your plugin, add the authorization header in onRequest callback:

export default ({ $axios }) => {
  $axios.onRequest(config => {
    config.headers.common['Authorization'] = 'Basic {your base64 encoded username/password here}'
  })
}

Although it's not recommended to put your login credential directly in the source code, using environment variables would be more appropriate, but that's another topic, you can check here https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-env/ if you are interested.

In terms of CORS error, it basically means the browser does not allow JavaScript to communicate with a remote server with different domain/port/schema (origin), unless the remote server responds with a matching origin in the Access-Control-Allow-Origin header. A simple fix would be adding Access-Control-Allow-Origin: * header in your server response if you have control of the server, but you can search it for some more details, there are different solutions to this issue and may fit better with your specific circumstance.

To access global, you need to use this.$axios and you don't need to import it somewhere else.

Related