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

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

问题描述

我将axios用于反应应用程序,我想记录我在应用程序中任何位置进行的所有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', request)
  return request
})

axios.interceptors.response.use(response => {
  console.log('Response:', response)
  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天全站免登陆