【问题标题】:How can I override the set axios override defaults on specific requests?如何在特定请求上覆盖设置的 axios 覆盖默认值?
【发布时间】:2017-11-01 19:31:20
【问题描述】:

当使用 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
})

【问题讨论】:

    标签: javascript axios


    【解决方案1】:

    您可以为每个 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)
      })
    

    【讨论】:

    • 这很有意义!所以假设我将我的实例命名为“帖子”,我会调用 posts.get() 而不是 axios.get()
    • @alilland 是的,您可以将posts 视为axios(除了少数例外,例如.all
    猜你喜欢
    • 2020-02-05
    • 1970-01-01
    • 2011-12-20
    • 2022-01-14
    • 2015-06-30
    • 2018-02-21
    • 1970-01-01
    相关资源
    最近更新 更多