【问题标题】:How to call external api's data from backend to frontend side?如何从后端调用外部api的数据到前端?
【发布时间】:2021-09-11 11:18:36
【问题描述】:

我正在尝试在后端部分使用 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 文件。因此,我尝试在app.get('/', (req, res)) 函数中编写res.sendFile((__dirname + '/index.html'));。但是,在这种情况下,我只能看到 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;
.
.
.
.
}

【问题讨论】:

  • 您正在尝试发送weatherDetail,但没有这样的变量
  • 是的,我添加到我的代码中但我忘了写在这里.. 我写了这个 -> let weatherDetail = resp.data;所以有一个变量
  • 前端不需要 axios,因为它们已经是浏览器 API,您可以使用它们。看看MDN Ajax
  • 发布了一个解决方案,它有效吗?

标签: node.js express axios weather-api pure-js


【解决方案1】:

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

【讨论】:

  • 感谢支持..我用车把
  • 很高兴看到它有效,您可以接受它作为一种解决方案,以便它可以在未来帮助其他人:)
【解决方案2】:

如果您使用 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(...);

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

【讨论】:

  • 您好,感谢您的解释,但我的领导希望我使用纯 js 而不是在前端使用框架。今天,我解决了它的问题。
  • 很高兴你解决了它。几个月前我问过同样的问题:) stackoverflow.com/questions/63353801/…
猜你喜欢
  • 2017-02-03
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
相关资源
最近更新 更多