【问题标题】:Check Axios request url before sending发送前检查 Axios 请求 url
【发布时间】:2018-10-22 03:10:02
【问题描述】:

API 请求失败,因为我的配置导致 Axios 生成的 URL 不正确。我知道请求 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,
  })
}

【问题讨论】:

    标签: javascript google-maps react-native axios


    【解决方案1】:

    您可以打开调试模式并查看另一个答案中提到的网络选项卡,或者您可以拦截 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。我尝试使用拦截器,但没有从中得到任何东西。
    • 拦截器正在工作。问题是尝试执行 (...args) 会导致获取数组,从而导致未定义的参数,从而出错。
    【解决方案2】:

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

    【讨论】:

    • 它实际上并没有使用baseURL,这是一种耻辱。
    • 有一个 pull request 开了几个月来解决这个问题,希望它会很快得到解决。
    • 直到那时:config.baseURL.replace(/\/+$/, '') + $axios.getUri(config) // 绝对 URL
    猜你喜欢
    • 2021-11-08
    • 2019-11-18
    • 2020-11-24
    • 2021-08-20
    • 2010-12-10
    • 1970-01-01
    • 2015-02-07
    • 2020-05-12
    • 2020-04-02
    相关资源
    最近更新 更多