如何覆盖特定请求的设置 axios 覆盖默认值?
How can I override the set axios override defaults on specific requests?
使用 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)
})
使用 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)
})