gpt4 book ai didi

node.js - Axios - 防止在外部 api 调用上发送 JWT token

转载 作者:行者123 更新时间:2023-12-02 02:10:55 26 4
gpt4 key购买 nike

我正在使用 nuxt + express 构建一个全栈应用程序,并且我终于成功地在我的前端/后端之间使用护照和 jwt 进行身份验证。

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

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

示例:

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

最佳答案

转换请求

您可以通过将选项对象传递给您的获取请求并转换您的请求 header 来覆盖特定调用的授权:

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 调用与不需要授权 header 的 axios 调用分开。每个实例都有自己的“全局”选项:

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

关于node.js - Axios - 防止在外部 api 调用上发送 JWT token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67764511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com