'Nuxt + Axios as plugin Request Failed 404

So I've started to try nuxt and I'm at a point where I need axios but I can't use nuxt's axios module.

Here's the files

nuxt.config.js

module.exports = {
  generate: {
    routes: ['/']
  },
  head: {
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Flynd FMS' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  loading: { color: '#3B8070' },
  modules: [
    '@nuxtjs/router',
    '@nuxtjs/dotenv'
  ],
  plugins: [
    {src: '@/plugins/axios.js', ssr: true},
    {src: '@/plugins/vuex-router-sync.js', ssr: false}
  ],
  build: {
    vendor: ['axios'],
    extend (config, ctx) {
      if (ctx.dev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
}

plugins/axios.js

import axios from 'axios'

const instance = axios.create({
  baseURL: process.env.API_HOST + ':' + process.env.API_PORT,
  transformRequest: function (request) {
    return request
  }
})

export default instance

pages/Login.vue

<template>
</template>
<script>
</script>

In this state, the axios instance should have not been called even once, but strange thing that it produces an error page mentioning Request failed with status code 404

Error page

I suspected that it tried to hit axios's baseUrl, and I had it confirmed by checking nginx access log.

Is this an expected behavior? If not, can anyone point me how to avoid this?

Thanks!

Update

Okay, I got it working few minutes after posting this out by changing the ssr to false

nuxt.config.js

module.exports = {
    plugins: [
        {src: '@/plugins/axios.js', ssr: false}
    ]
}

But I'll keep this question open since that behavior in ssr mode still unexpected.



Solution 1:[1]

If you are using the latest version on nuxt.js it will which module to install. Just Select the "Axios" by hitting space then you are good to go.

See Img here

Then you can make a global function for all your calls.


This is a global function for all get calls.
Don't forget to include this file in middleware folder.

getReq: async function (apiUrl, reqHeader) {
return await axios
  .get(apiUrl, reqHeader)
  .then((response) => {
    console.log('Response from', apiUrl, ':', response)
    return response
  })
  .catch((err) => {

    if(err.response.data.error === 'session data missing'){
      console.log("this:",this);
      console.log("Error:",err.response.data.error);
      // Popup Msg
      Snackbar.open({
        duration: 5000,
        message: 'Session Error! Please Sign Again',
        type: 'is-warning',
        position: 'is-top-right',
        actionText: 'Ok',
        indefinite: false,
        onAction: () => {
          console.log("pap",location);

          location.replace("/")
        }
      })

    }
    return err.response
  })
},

This is how the global funtion is called.

const contractList = {
      headers: {},
      params: {
        id: null,
        state: this.state
      },
      withCredentials: true
    }

    const response = await ApiService.getReq(LIST_CONTRACT, contractList)
    console.log('Response from getList', response)

Solution 2:[2]

The problem is with axios.

Handling of async request can cause this issue. In my case, one of the external apis being used was down which was causing axios to fail.

Steps to debug and resolve this:

  • Identify where all is axios being used
  • Check if the apis are returning the correct response (check this outside of the project)
  • If required, comment apis and check which one if the api causing the issue
  • Additionally interceptors can be used to capture the error and show proper stack trace as done here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shrish Ankit
Solution 2 Vaulstein