首页 > 解决方案 > axios 没有从 openweathermap api 返回数据

问题描述

我正在尝试从 openweathermap api 获取数据。我很容易使用邮递员获得它,但我尝试使用带有 axios 请求的 nodejs 并且它以 400 状态代码响应。我为此编写了以下代码-

try {
      let a = 'london'

      const data = await axios.get(
        `api.openweathermap.org/data/2.5/weather?q=${a}&appid=${process.env.WEATHER_API_KEY}`
      )
      console.log('the data is', data)

      if (data) {
        console.log('the data is', data)
        res.status(201).json(data)
      }
    } catch (error) {
      console.log('error', error.message)
      res.status(403)
      res.json(error)
    }

标签: node.jsapi

解决方案


您需要在网址中添加http://或。https://没有它们,URL 的格式不正确,axios 认为它​​是一个相对 URL(例如/local/api),但是因为您尝试在节点上执行它,所以它没有像在浏览器中那样的“相对”上下文(站点来源)。


推荐阅读