javascript - 卡在将数据传递到“收藏夹”列表中,需要提示
问题描述
今天我面试的一家公司给了我一个编码练习。它只是一个从 openweathermap api 中提取数据的简单天气应用程序。我已经使用 express、node 和 ejs 编写了所有后端逻辑(这是测试的目的)。但是,该公司希望我为 index.html(或我的情况下的 index.ejs)使用预制的 Bootstrap 模板。布局很简单。我坚持的是有一个按钮可以将城市添加到收藏夹列表中。然后有一个显示收藏夹的列表。
我需要帮助实现此按钮的功能。我敢肯定这似乎是一个非常菜鸟的问题,但我完全被这部分困住了。
因此,当用户单击“添加到收藏夹”按钮时,我需要动态填充以下列表:
<a href="#" class="list-group-item list-group-item-action">Miami Beach Florida
button type="button" class="btn btn-default" style="display: inline; float: right;">X</button></a>
<a href="#" class="list-group-item list-group-item-action">Austin Texas
<button type="button" class="btn btn-default" style="display: inline; float: right;">X</button></a>
<a href="#" class="list-group-item list-group-item-action">Williamsburg Virginia
<button type="button" class="btn btn-default" style="display: inline; float: right;">X</button></a>
</ul>
这是按钮:
<button type="submit" class="btn btn-primary">Add To Favorites!</button>
后端代码:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const fetch = require('node-fetch');
const request = require('request');
const api_key = 'a8b497ec94fc3d6f1a14044d575f5bca';
app.set('view engine', 'ejs')
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
res.render('index', {
city: null,
description: null,
humidity: null,
temp: null,
wind: null,
precipitation: null
})
})
app.post('/', async function (req, res) {
const zipcode = req.body.zipcode;
const url_api = `https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&appid=${api_key}`
console.log(req.body.zipcode);
try {
await fetch(url_api).then(res => res.json())
.then(data => {
if(data.message === "city not found") {
res.render('index', {
city: data.message,
description: null,
humidity: null,
temp: null,
wind: null,
precipitation: null
})
} else {
const city = data.name;
const description = data.weather[0].description;
const wind = data.wind.speed;
const temp = data.main.temp;
const humidity = data.main.humidity;
const precipitation = data.rain;
res.render('index', {
city, description, wind, temp, humidity, precipitation
});
}
});
} catch(err) {
res.render('index', {
city: 'There was an error',
description: null,
humidity: null,
temp: null,
wind: null,
precipitation: null,
})
}
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
解决方案
推荐阅读
- adobe - 如何计算和显示当前文档中的笔触次数?
- python - 进行 RSA 加密然后解密 AES 密钥的奇怪错误
- javascript - 停止在浏览器上长时间运行的 javascript 函数
- javascript - 如何检查我的变量是一个字还是两个字长
- sql - DB引擎如何决定JOIN操作的查询计划?
- java - 解析 application.yml
- php - 在网络服务器上分发 APK
- discord - 如何检查文本频道的权限值?[不和谐.py]
- swiftui - 如何将点击手势识别器添加到 SecureField 以使识别器的点击区域与字段的默认点击识别器相同?
- c# - 无法解析请求正文。确保请求正文与指定的内容类型匹配:application/json