我正在尝试使用{
"城市":["toronto";,"孟买";,"伦敦";]}作为输入并返回
{
"weather": {
"toronto": "24C",
"mumbai": "34C",
"london": "14C"
}
}
作为输出
app.post('/getWeather',(req,res)=>{
const city = req.body.city;
city.map(city=>{
const url=`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.WEATHER_API_KEY}`;
request(url, function(err, response, body) {
// On return, check the json data fetched
if (err) {
res.render('index', { weather: null, error: 'Error, please try again' });
} else {
let weather = JSON.parse(body);
console.log(weather);
由于问题中没有所有的代码,我无法给出确切的答案,但我假设代码要么尝试单独发送每个城市的响应,要么不等待所有API调用完成。
为了解决这个问题,需要使用async/await(因为响应依赖于几个API调用(,并且必须在完全组装后发送响应。
基于给定代码的示例:
app.post("/getWeather", async (req, res) => {
const cities = req.body.cities;
const reqs = cities.map((city) => {
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.WEATHER_API_KEY}`;
return new Promise((resolve, reject) => {
request(url, function (err, response, body) {
if (err) {
reject(err);
} else {
let weather = JSON.parse(body);
resolve(weather);
}
});
});
});
const responses = await Promise.all(reqs);
const result = {};
for (const response of responses) {
if (response.ok) {
result[response.city] = response.temp;
}
}
res.json(result);
});