我使用 Axios 进行 API 调用,这里我为每个 API 调用(授权事物)中的公共(public) header 创建了实例。
export const axiosInstance = axios.create({
baseURL: 'demo API'
})
axiosInstance.interceptors.request.use(function (config) {
config.headers['Accept'] = 'application/json'
config.headers['testkey'] = 'randomdata'
return config
}, function (err) {
return Promise.reject(err)
})
现在可以打电话
return axiosInstance.post('/api/demo, {myCommonBody})
.then(data => {
//action and action..
})
.catch(err => {
throw err;
});
这里我必须在所有 API 主体中传递 myCommonBody
。
但是这些东西我也需要在拦截器中是通用的(就像我在 header 中所做的那样)。
因此,每当我们使用通用 API 实例调用任何 API 时,这里都会默认获取 BODY 部分。
任何领导都感谢您的回答。 谢谢。
最佳答案
axiosInstance.interceptors.request.use(function (config) {
config.headers['Accept'] = 'application/json'
config.headers['testkey'] = 'randomdata'
config.data = Object.assign({}, config.data, {myCommonBody});
return config
}, function (err) {
return Promise.reject(err)
})
或
export const axiosInstance = axios.create({
baseURL: 'demo API',
data: {myCommonBody}
})
关于javascript - API 调用主体有效负载的 Axios 实例(为所有 API 创建通用对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55904939/