使用 axios 承诺库时,它允许您设置查询默认值以用于所有请求,如下所示:
axios.defaults.baseURL = 'localhost:3000'
axios.defaults.headers.common['Token'] = window.localStorage.authtoken || null
axios.defaults.headers.post['Content-Type'] = 'application/json'
Run Code Online (Sandbox Code Playgroud)
这很好,虽然只有一个 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
})
Run Code Online (Sandbox Code Playgroud)
您可以为每个 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'
})
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用所有 axios 方法,例如.get和.post在这些实例上:
firstAPI.get('hello')
.then((response) => {
console.log(response)
})
secondAPI.post('world')
.then((response) => {
console.log(response)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5336 次 |
| 最近记录: |