如何在代码中记录从一个位置发出的所有 Axios 调用

我正在使用一个反应应用程序的公理,我想记录所有的公理调用,我在应用程序的任何地方。我已经通过 create 函数使用了一个全局 Axios 实例,并且能够记录一个通用的 console.log。然而,我想要更多的信息,如函数被调用,参数等。

123545 次浏览

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

您可以尝试将 axios.request函数包装在一个项目中。

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

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

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

或者类似的东西。

使用新的公理实例是件好事:

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

这样你就能打电话了

api.interceptors[...]

使用 axios-debug-log

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

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

  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

有关配置和自定义选项,请参阅 那些文件

下面是一个针对 MySQL 的 NPM 包,它可以让您记录所有的 Axios 请求 https://www.npmjs.com/package/axios-logger-mysql,我希望这有所帮助。

使用 Axios-Logger

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