How to log all axios calls from one place in code

前端 未结 6 1148
佛祖请我去吃肉
佛祖请我去吃肉 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:49

    Here's an NPM package for MySQL that let's you log all axios requests https://www.npmjs.com/package/axios-logger-mysql , I hope this helps.

    0 讨论(0)
  • 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[...]
    
    0 讨论(0)
  • 2021-01-30 12:56

    Use axios-debug-log

    1. npm install --save axios-debug-log
    2. require('axios-debug-log') before any axios call
    3. Set the environment variable DEBUG=axios

    By default, you'll see logs like the following:

      axios POST /api/auth/login +0ms
      axios 200  (POST http://localhost:8080/api/auth/login) +125ms
      axios POST /api/foo +0ms
      axios 200  (POST http://localhost:8080/api/foo) +15ms
    

    Refer to the docs for configuration and customization options.

    0 讨论(0)
  • 2021-01-30 13:04

    It looks like you can intercept all requests using an "interceptor", and log inside of it: https://github.com/mzabriskie/axios#interceptors

    0 讨论(0)
  • 2021-01-30 13:04

    Use axios-logger

    When you send a request in nodejs, you need to show the log to the console.

    0 讨论(0)
  • 2021-01-30 13:06

    You can try wrap the axios.request function in a Promise.

    function loggedRequest(config) {
      return new Promise((resolve, reject) => {
        axios.request(config)
        .then((res) => {
          // log success, config, res here
          resolve(res);      
        })
        .catch(err => {
          // same, log whatever you want here
          reject(err);
        })
      })
    }
    
    0 讨论(0)
提交回复
热议问题