如何从代码中的一处记录所有 axios 调用 [英] How to log all axios calls from one place in code

查看:20
本文介绍了如何从代码中的一处记录所有 axios 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 the create function and I am able to log a generic console.log. However I would like more info like function being called, parameters, etc.

推荐答案

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

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

或类似的东西.

很高兴您使用的是 axios 的新实例:

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

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

这样你就可以打电话了

api.interceptors[...]

这篇关于如何从代码中的一处记录所有 axios 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆