Axios - 防止在外部 api 调用上发送 JWT 令牌

Axios - Prevent sending JWT token on external api calls

我正在使用 nuxt + express 构建一个全栈应用程序,我终于设法在我的 frontend/backend with passport 和 jwt 之间添加了身份验证。

我想向我自己的 github 存储库发出额外的 api 请求以获取最新版本(以便用户获得存在更新的信息)。此请求失败,并显示“凭据错误”消息。我认为发生这种情况是因为我的 jwt 令牌与它一起发送(我可以在请求中看到我的令牌 header)。

我的问题是,是否可以阻止 axios 仅在这次调用中发送我的 JWT 令牌?首先,为了使我的请求有效,其次,我不希望在外部请求中发送令牌。

示例:

const url = 'https://api.github.com/repos/xxx/releases/latest'
this.$axios.get(url)
    .then((res) => {
        this.latestRelease = res.data
    }).catch((error) => {
        console.error(error)
    })

转换请求

您可以通过将选项 object 传递给您的获取请求并 转换 您的请求 header 来覆盖特定调用的 Authorization小号:

const url = 'https://api.github.com/repos/xxx/releases/latest';
this.$axios.get(url, {
  transformRequest: (data, headers) => {
    delete headers.common['Authorization'];
    return data;
  }
})
.then((res) => {
  this.latestRelease = res.data;
}).catch((error) => {
  console.error(error);
})

正如他们在 GitHub readme 中所解释的那样:

transformRequest allows changes to the request data before it is sent to the server. This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'. The last function in the array must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream. You may modify the headers object.

创建特定实例

您可以create an instance of axios针对不同的场景。这允许您将需要授权 header 和不需要授权的 axios 调用分开。每个实例都有自己的 'global' 选项:

const axiosGitHub = axios.create({
  baseURL: 'https://api.github.com/',
  timeout: 1000,
  headers: {}
});

// won't include the authorization header!
const data = await axiosGithub.get('repos/xxx/releases/latest');

您可以使用此答案来获得多个 axios 实例:

或者你也可以像这样导入一个全新的 axios 并在本地使用它

<script>
import axios from 'axios'

export default {
  methods: {
    async callFakeApi() {
      const result = await axios.get('https://jsonplaceholder.typicode.com/todos/1')
      console.log('result', result)
    },
  }
}
</script>

Thatkookooguy 提到的 Axios 拦截器是另一种解决方案!