【发布时间】:2021-09-11 11:18:36
【问题描述】:
我正在尝试在后端部分使用 node、express 和 Axios 来应对 Api 应用程序,而不使用 Angular 或 react 等任何框架。
我的代码有 3 个主文件。
- index.html
- customer.js(用于前端部分)
- 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