How to log all axios calls from one place in code

前端 未结 6 1147
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 12:17

I am using axios for a react application and I would like to log all axios calls that I\'m making anywhere in the app. I\'m already using a single global instance of axios via t

6条回答
  •  被撕碎了的回忆
    2021-01-30 12:56

    The best way to do this would be an interceptor. Each interceptor is called before a request/response. In this case a logging interceptor would be.

    axios.interceptors.request.use(request => {
      console.log('Starting Request', JSON.stringify(request, null, 2))
      return request
    })
    
    axios.interceptors.response.use(response => {
      console.log('Response:', JSON.stringify(response, null, 2))
      return response
    })
    

    or something to that effect.

    It's good that you're using a new instance of axios:

    const api = axios.create({
      timeout: 1000
    })
    

    That way you can call

    api.interceptors[...]
    

提交回复
热议问题