[Vuejs]-Axios local API call in Nuxt Middleware or nuxtServerInit() action returns a 404 error on server side only

0👍

I had a somewhat similar issue with my nuxt middleware function used for user persistence. The nuxt server will create and render the requested page without taking your external api response into account if you don’t return the promise or use async await.

For Example: Here I have a synchronous function that utilizes an axios promise to set vuex data. You have to return the axios promise.

export default function (context) {
        console.log('Persistence Middleware');
        // No need for request, we have a user object
        if (context.store.state.user) {
            return;
        }

        let token;

        if (process.server) {
            console.log('Persistence Server');
            const headers = context.req.headers.cookie;    
            if (!headers) {
                return;
            }
            token = headers.split('=')[0] === 'token' ? headers.split('=')[1] : null;
        }

        if (process.client) {
            console.log('Persistence Client');
            token = getCookie('token');
        }

        if (token) {
            console.log('Persistence Token', token);
              
            context.$axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
            return context.$axios.$get('/api/v1/userprofile/me')
                .then(res => {

                    console.log({ res }, 'middleware res');
                    context.store.commit('setUser', res);
                 
                })
                .catch(err => {
                    console.log({ err }, 'middleware err');
                });
        }
}

Here I utilize async/await without returning.

export default async function (context) {
    try {
        console.log('Persistence Middleware');
        // No need for request, we have a user object
        if (context.store.state.user) {
            return;
        }

        let token;

        if (process.server) {
            console.log('Persistence Server');
            const headers = context.req.headers.cookie;
            if (!headers) {
                return;
            }
            token = headers.split('=')[0] === 'token' ? headers.split('=')[1] : null;
        }

        if (process.client) {
            console.log('Persistence Client');
            token = getCookie('token');
        }

        if (token) {
            context.$axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;

            const res = await context.$axios.$get('/api/v1/userprofile/me');
            context.store.commit('setUserData', res);
            console.log(res, 'middleware res');
        }

    } catch (error) {
        console.log({ error }, 'middleware error');
    }
}

0👍

I solved this (with help!) using the options documented here:

  publicRuntimeConfig: {
    axios: {
      baseURL: `http://localhost:${process.env.PORT || '3000'}/`, // server
      browserBaseURL: '/', // client / browser
    }
  },

How it works:

  • server: uses http://localhost + the port (either the 8080 supplied by Azure, or default 3000 in development)
  • client: uses the protocol and domain in the URL

I don’t even have an axios node in my nuxt.config.js – this is the entirety my Axios configuration.

My setup is:

  • express back end running at server/index.js
  • local API at /api/
  • uses nuxtServerInit() to fetch data before rendering the page

Deployment:

  • running on Azure
  • behind authentication

Scripts:

  • build command: npm run generate
  • startup command: npm run start

And it works great… after days of messing around and working all this out.

Leave a comment