简体   繁体   English

如何将基本身份验证与 axios nuxt 模块一起使用

[英]How to use basic auth with axios nuxt module

I am currently struggling with Nuxt's Axios module: https://axios.nuxtjs.org/ .我目前正在努力使用 Nuxt 的 Axios 模块: 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:通常,使用 Axios,我会执行以下操作:

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:不幸的是,使用 Nuxt 的 Axios 模块,似乎并不那么容易......我尝试了类似的东西:

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

But that leaves me with a 401 Unauthorized ...但这给我留下了401 Unauthorized ...

What am I missing here?我在这里想念什么?

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). axios.get() (和$axios.$get() )的第二个参数是Axios config ,但您已将其作为第三个参数传递(实际上已被忽略)。 The API likely omits the data argument from axios.get() because data doesn't apply in this context. API 可能会省略axios.get()中的数据参数,因为数据不适用于此上下文。

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'
    }
  }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM