从axios返回数据,以便通过车把在屏幕上显示



我有一个基本的Node Js应用程序,我想在其中显示给定位置的天气

app.post("/weather",(req,res)=>{
res.render('weather.hbs',{
temperature:fetchLocation(req.body.location),
location:req.body.location
});
});

我还有一个函数fetchLocation,它使用axios从api 中提取数据

function fetchLocation(location){
const encodedLocation = encodeURIComponent(location);
const url = `https://api.openweathermap.org/data/2.5/weather? 
q=${encodedLocation}&units=metric&appid=ID`;
return axios.get(url)
.then(response=>{
response.data.main.temp;
})
.catch(error=>{
console.log(error.message);
});
}

我无法从axios获得数据,它正在返回undefiend或Promise等待

您需要使用return语句从类似的promise返回一个值

您还应该等待结果,以便能够将其发回。您可以使用async/await或在收到数据后调用res.render((函数来轻松实现,如:

fetchLocation().then(data => res.render({ ... })
function fetchLocation(location){
const encodedLocation = encodeURIComponent(location);
const url = `https://api.openweathermap.org/data/2.5/weather? 
q=${encodedLocation}&units=metric&appid=ID`;
return axios.get(url)
.then(response=>{
-------------------------->  return response.data.main.temp;
})
.catch(error=>{
console.log(error.message);
});
}
// with async / await
app.post("/weather",async (req,res)=>{
res.render('weather.hbs',{
temperature: await fetchLocation(req.body.location),
location:req.body.location
});
});
// OR without
app.post("/weather",(req,res)=>{
fetchLocation(req.body.location).then(data => {
res.render('weather.hbs',{
temperature: data,
location:req.body.location
});
})
});

最新更新