gpt4 book ai didi

javascript - 如何覆盖特定请求的设置 axios 覆盖默认值?

转载 作者:行者123 更新时间:2023-11-30 14:57:12 24 4
gpt4 key购买 nike

当使用 axios promise 库时,它允许您设置查询默认值以用于所有请求,如下所示:

axios.defaults.baseURL = 'localhost:3000'
axios.defaults.headers.common['Token'] = window.localStorage.authtoken || null
axios.defaults.headers.post['Content-Type'] = 'application/json'

虽然只有一个 API 可以查询,但现在我有多个 API,我的客户端应用程序需要与之交互,有没有办法用它们自己的配置来设置多个 baseURL?或者有没有办法告诉 axios 忽略特定请求的默认值?

// on specific urls I want to override the default base URL
axios.get('localhost:9000/whatever_resource')
.then(result => {
// whatever
})
.catch(error => {
// whatever
})

最佳答案

您可以为每个 API 设置一个实例,使用它们自己的基本 URL:https://github.com/axios/axios#creating-an-instance

const firstAPI = axios.create({
baseURL: 'http://first-api.com'
})
const secondAPI = axios.create({
baseURL: 'http://second-api.com'
})

然后您可以在这些实例上使用所有的 axios 方法,例如 .get.post:

firstAPI.get('hello')
.then((response) => {
console.log(response)
})

secondAPI.post('world')
.then((response) => {
console.log(response)
})

关于javascript - 如何覆盖特定请求的设置 axios 覆盖默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47062335/

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