1

我正在使用 Axios 进行 API 调用,在这里我为每个 API 调用(授权事物)中的公共标头创建了实例。

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;
  }); 

在这里,我必须传递myCommonBody所有 API 正文。

但是这些东西我也需要在拦截器中通用(就像我所做的标题一样)。

因此,每当我们使用通用 API 实例调用任何 API 时,这里我们默认获取 BODY 部分。

任何领导都感谢您的回答。谢谢。

4

2 回答 2

1

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}
})

于 2019-04-29T15:38:37.637 回答
0
export const axiosInstance = axios.create({
  baseURL: 'demo API',
  data: {'myCommonBody': 'myCommonBodyDetails')
})

并且为每个 api 调用都设置好了。

于 2019-04-29T15:07:19.080 回答