我正在使用 axios 作为 React 应用程序,我想记录我在应用程序中任何位置进行的所有 axios 调用。我已经通过 create 函数使用了 axios 的单个全局实例,并且我能够记录通用的 console.log。但是我想要更多信息,例如被调用的函数、参数等。
做到这一点的最好方法是拦截器。每个拦截器在请求/响应之前被调用。在这种情况下,日志拦截器将是:
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['...']
axios-debug-log
npm install --save axios-debug-log
require('axios-debug-log')
在任何 axios 调用之前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
请参阅文档了解配置和自定义选项。
看起来您可以使用“拦截器”拦截所有请求,并登录其中:https://github.com/mzabriskie/axios#interceptors
在nodejs中发送请求时,需要将日志显示到控制台。
您可以尝试将
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);
})
})
}
这里有一个 MySQL 的 NPM 包,可让您记录所有 axios 请求 https://www.npmjs.com/package/axios-logger-mysql ,我希望这会有所帮助。