首页 > 解决方案 > 如何让 axios 在 node.js 应用程序中工作

问题描述

我正在尝试在 node.js 应用程序中使用 axios 进行 api 调用。通过将函数放在 app.js 文件中并将其链接到 html 文件,我可以让 axios 在 node.js 之外工作。但是,我似乎无法让它在 node.js 环境中工作。现在,我在控制器文件夹中的一个名为“weather.js”的文件中有 api。

当我从控制台调用这个函数时,它说 getWeather 没有定义。我可以让这个函数在 Node.js 环境之外工作。

const axios = require('axios');

function getWeather(lat, long) {
    const key = OPEN_WEATHER_KEY;
    const url = `http://api.openweathermap.org/data/2.5/weather? 
          lat=${lat}&lon=${long}&appid=${key}&units=imperial`;

    axios
   .get(url)
   .then(function (response) {
     // handle success
     console.log(response);
     console.log(response.data.name);
     console.log(response.data.main.temp);
     console.log(response.data.weather[0].description);
   })
   .catch(function (error) {
      // handle error
      console.log(error);
   })
   .then(function () {
      // always executed
  });
}

标签: javascriptnode.jsaxios

解决方案


推荐阅读