title: Taro.addInterceptor(callback)

sidebar_label: addInterceptor

Minimum Taro version: 1.2.16

Interceptors can be used to perform additional actions before or after the request is made.

Before calling Taro.request to initiate the request, the Taro.addInterceptor method is called to add an interceptor to the request. In addition, the order in which interceptors are called follows the onion model.

Taro provides two built-in interceptors, logInterceptor and timeoutInterceptor, which are used to print information about the request and to throw an error if the request times out, respectively.

Type

  1. (callback: Function) => void

Parameters

Property Type
callback Function

Sample Code

Example 1

  1. const interceptor = function (chain) {
  2. const requestParams = chain.requestParams
  3. const { method, data, url } = requestParams
  4. console.log(`http ${method || 'GET'} --> ${url} data: `, data)
  5. return chain.proceed(requestParams)
  6. .then(res => {
  7. console.log(`http <-- ${url} result:`, res)
  8. return res
  9. })
  10. }
  11. Taro.addInterceptor(interceptor)
  12. Taro.request({ url })

Example 2

  1. Taro.addInterceptor(Taro.interceptors.logInterceptor)
  2. Taro.addInterceptor(Taro.interceptors.timeoutInterceptor)
  3. Taro.request({ url })

API Support

API WeChat Mini-Program Baidu Smart-Program Alipay Mini-Program ByteDance Mini-Program QQ Mini-Program H5 React Native
Taro.addInterceptor ✔️ ✔️ ✔️ ✔️ ✔️ ✔️