R
R
Renhor2019-12-21 12:46:31
Vue.js
Renhor, 2019-12-21 12:46:31

How to correctly set axios.baseUrl in Nuxt, what would work on both local and domain?

Good afternoon! Initially it was like this:

axios: {
    baseURL: process.env.NODE_ENV === 'production'
      ? 'https://site-name.ru'
      : 'http://localhost:3000'
 },

My joy knew no bounds until I accidentally went to www .site-name.ru and discovered that requests go to a domain without www and are blocked by CORS policy => the domain with www becomes inoperable.
Next I tried:
axios: {
    baseURL: '/'
 },

But even here the moment - the code from nuxtServerInit stops working correctly.
nuxtServerInit:
async nuxtServerInit({ dispatch, getters, commit }) {
    const isUserSigned = await dispatch('auth/autoSignin');

    if (isUserSigned) await dispatch('auth/getUserByToken');
}

store/auth
async getUserByToken({commit, dispatch}) {
    try {
      const user = await this.$axios.$get('/api/auth/getUserByToken');

      if (user && user.id) {
        dispatch('setUser', user);
      } else {
        dispatch('signout', false);
      }

    } catch (e) {
      console.log(e.message);
      dispatch('setUser', null);
      dispatch('signout', false);
    }
},

That is, the response from the server is 404 because the request is sent to http:/api/auth/getUserByToken' (literally).
With the rest of the requests, everything is in order, in any case, so far the problem is relevant only for nuxtServerInit.
What do you advise?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question