简体   繁体   中英

Return data from axios in order to display it on screen through handlebars

I have basic Node Js app in which I want to display weather for given location I have this post route which is rendering weather page with given objects:

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

And also I have function fetchLocation which is using axios to fetch data from 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);
                          });
                          }

I am not able to get data from axios it is returning undefiend or Promise pending

You need to use the return statement to return a value from a promise like so

You should also await the result to be able de send it back. You can achieve easily with async/await or by calling the res.render() function after receiving the data like so:

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
                   });
})
                 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM