发送 Axios 请求前检查 URL

15

由于我的配置问题,Axios 生成的 URL 不正确,导致 API 请求失败。我知道请求 URL 应该是什么样子的,所以我想看看 Axios 生成的请求 URL。

我可以将 Axios 指向本地服务器并在那里查看请求,但我想在客户端调试此问题。我想尝试不同的配置,看看请求会如何更改。有办法在发送请求前或后从 Axios 输出请求 URL 吗?

// param format
{ address: 'Vancouver', key: GOOGLE_API_KEY }

// Geocode sample
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

_request = async (...args) => {
  const { outputFormat, params } = args
  const instance = axios.create({
    baseURL: `https://maps.googleapis.com`,
  })

  const response = await instance.get('/maps/api/geocode/${outputFormat}?', {
    params,
  })

  // I want to see the url generated by Axios so I can debug the issue

  console.log(response) 
}

我处于 ExpoReact Native 环境中。

使用 fetch 的工作示例:

const url = `https://maps.googleapis.com/maps/api/geocode/json?address=vancouver&key=${GOOGLE_API_KEY}`

fetch(url)
  .then((response) => response.json())
  .then((data) => {
    console.log(data)
  })
  .catch(function(error) {
    console.log(error)
  })

使用的解决方案:

_request = async (obj) => {
  const { outputFormat, params } = obj

  const instance = axios.create({
    baseURL: `https://maps.googleapis.com`,
  })

  instance.interceptors.request.use(function (config) {
    console.log(config)
    return config
  }, function (error) {
    return Promise.reject(error)
  })

  const response = await instance.get(`/maps/api/geocode/${outputFormat}`, {
    params,
  })
}
2个回答

22

你可以像其他答案中提到的那样打开调试模式并查看网络标签,或者你可以拦截axios并在发送请求之前使用console.log或执行任何你想要的操作:

你可以打开调试模式并查看网络标签,或者你可以拦截axios并在发送请求之前使用console.log或执行任何你想要的操作。

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    console.log(config)
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

我收到了一个状态码为400的请求失败。我尝试使用拦截器,但是我从中没有得到任何东西。 - Dan
拦截器正在工作。问题在于尝试执行 (...args) 会得到一个数组,这将导致未定义的参数,从而出现错误。 - Dan

15
你可以使用axios#getUri([config])源代码)来执行与请求相同的逻辑。它合并配置(例如给定的config和实例配置)、将urlbaseURL合并,并使用paramSerializer附加任何params

1
实际上它没有使用baseURL,这很遗憾。 - utluiz
已经有一个拉取请求(pull request)在GitHub上开放了好几个月来解决这个问题,希望它能很快得到修复。 - utluiz
直到那时:config.baseURL.replace(/\/+$/, '') + $axios.getUri(config) // 绝对 URL - FooBar
baseURL问题已在0.26.1版本中得到修复:https://github.com/axios/axios/pull/3737 - Trevor Robinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接