How to use basic auth with axios nuxt module

Viewed 2944

I am currently struggling with Nuxt's Axios module: https://axios.nuxtjs.org/. I would like to get some data from a specific endpoint where I have to use Basic Authentication.

Normally, with Axios, I would do something like:

await axios.get(
  'http://endpoint',
  {},
  {
    withCredentials: true,
    auth: {
      username: 'userame',
      password: 'pw'
    }
  }
)

Unfortunately, with Nuxt's Axios module, it seems it is not that easy... I tried something like:

const data = await this.$axios.$get(
  'http://endpoint',
  {},
  {
    credentials: true,
    auth: {
      username: 'user',
      password: 'pw'
    }
  }
)

But that leaves me with a 401 Unauthorized...

What am I missing here?

1 Answers

The second argument to axios.get() (and $axios.$get()) is the Axios config, but you've passed it as the third argument (which is effectively ignored). The API likely omits the data argument from axios.get() because data doesn't apply in this context.

The solution is to replace the 2nd argument with your config:

const data = await this.$axios.$get(
  'http://endpoint',
  // {},          // <-- Remove this! 2nd argument is for config
  {
    credentials: true,
    auth: {
      username: 'user',
      password: 'pw'
    }
  }
)
Related