微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从后端调用外部api的数据到前端?

如何解决如何从后端调用外部api的数据到前端?

我正在尝试在后端使用 node、express 和 Axios 来适应 Api 应用程序,而不使用任何框架,如 Angular 或 react。

我的代码有 3 个主文件

  1. index.html
  2. customer.js(前端部分)
  3. server.js(后端部分)

我的后端部分如下;

const express = require('express');
const app = express();
const axios = require('axios').default;

API_KEY = "***";
const PORT =3000;

// app.use("/static",express.static(__dirname + '/customer'));

app.get('/',(req,res) =>{
    axios
      .get(`http://api.openweathermap.org/data/2.5/forecast?q=amsterdam&appid=${API_KEY}`)
      .then(resp => {
         let weatherDetail = resp.data;
         console.log('a single country details: ',weatherDetail);
         res.send(weatherDetail);
      })
      .catch(err => console.log(err));
  });

app.listen(PORT,() => console.log(`My app listening on port ${PORT}! `));

当我在浏览器上写 localhost:3000 时,我可以看到天气 api 的数据。但是我想在customer.js 和api 的数据中查看带有函数的html 文件。因此我尝试在 res.sendFile((__dirname + '/index.html')); 函数中编写 app.get('/',res))。但是,在这种情况下,我只能看到 html 页面,而无法从后端获取数据。

如何在 customer.js 文件调用从后端部分获取的数据?

我在 customer.js 中的代码如下(但我不确定我是否在这文件中使用了 axios agan)

const apiCall = cityName => {
    let apiKey = "***";
    let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}&units=metric`
    axios
        .get(apiUrl)
        .then(getWeather)
        .catch(err => {
            console.log(err);
            err.response.status === 404 ? alert(`The country ${cityName} doesn't exist.`) : alert('Server error! Sorry.');
        });
};
apiCall(amsterdam)

    function getWeather (response) {
        let city = document.querySelector("#city");
        city.innerHTML = response.data.name;
.
.
.
.
}

解决方法

我建议使用像 handlebarsejs 这样的模板引擎。关于它的例子有很多,在使用任何模板引擎时,将数据从后端发送到前端变得小菜一碟。我个人最喜欢的是handlebars,因为它的语法很简单。

,

如果您使用的是 Angular 或 React,建议不要使用 document.querySelector。每当有新数据可供更新时,React/Angular 都会通过在 index.html 文件的“根”div 元素中进行更新来让浏览器重新绘制 DOM。 另外,为什么要发送 HTML 文件?你可以在 Node 中有一个如下所示的路由

route.get('/weather',(req,res) => {
    // do your api call with axios to get weather data
   res.json(weatherData);
});

从您的前端,您可以对“/weather”路由进行 API 调用并使用 JSON 数据

axios.get('baseUrl/weather').then(res=>{
   console.log("weather data",res);
}).catch(...);

您也可以像上面一样直接从前端获取天气数据。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。