如何从代码中的一个位置记录所有 axios 调用

问题描述 投票:0回答:6

我正在使用 axios 作为 React 应用程序,我想记录我在应用程序中任何位置进行的所有 axios 调用。我已经通过 create 函数使用了 axios 的单个全局实例,并且我能够记录通用的 console.log。但是我想要更多信息,例如被调用的函数、参数等。

axios
6个回答
327
投票

做到这一点的最好方法是拦截器。每个拦截器在请求/响应之前被调用。在这种情况下,日志拦截器将是:

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

或类似的东西。

您正在使用 axios 的新实例,这很好:

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

这样你就可以打电话:

api.interceptors['...']

30
投票

使用
axios-debug-log

  1. npm install --save axios-debug-log
  2. require('axios-debug-log')
    在任何 axios 调用之前
  3. 设置环境变量
    DEBUG=axios

默认情况下,您将看到如下日志:

  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

请参阅文档了解配置和自定义选项。


6
投票

看起来您可以使用“拦截器”拦截所有请求,并登录其中:https://github.com/mzabriskie/axios#interceptors


3
投票

使用axios-logger

在nodejs中发送请求时,需要将日志显示到控制台。


1
投票

您可以尝试将

axios.request
函数包装在 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);
    })
  })
}

-12
投票

这里有一个 MySQL 的 NPM 包,可让您记录所有 axios 请求 https://www.npmjs.com/package/axios-logger-mysql ,我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.