Return value from a request!

Asked

Viewed 667 times

0

I’m practicing some nodejs, so I decided to create an application for the temperature consultation, but I came across a question. How do I return the value of the variable "Weather":

const tempo = () =>{
    request(`http://apiadvisor.climatempo.com.br/api/v1/locale/city?name=Joinville&state=SC&token=${TOKEN}`, (error, response, body) =>{ 
        const id = JSON.parse(body)[0]["id"]
        request(`http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/${id}/days/15?token=${TOKEN}`, (error,response, body) =>{
            const weather = JSON.parse(body)
        })
  })
}
  • console.log(weather) returns nothing?

  • It is important that you do not put in your question the image of the code but the code itself, making it easier for those who may answer.

  • So, yes, the console.log(Weather) works perfectly, but I wanted to take the value of the request out of the scope of the function. Of course, I’m starting with Ode itself now, so I don’t know if this is bad practice, or I’m using Ode wrong.

1 answer

0


If by "return" you mean "serve as an answer to a endpoint", you can use the express as follows:

const express = require('express');
const fetch = require('node-fetch');
const app = express();

const TOKEN = '[SEU TOKEN]';

app.get('/', async (req, res) => {
  try {
    const result = await fetch(`http://apiadvisor.climatempo.com.br/api/v1/locale/city?name=Joinville&state=SC&token=${TOKEN}`);
    const { 0: { id } } = result.text();
    const body = await fetch(`http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/${id}/days/15?token=${TOKEN}`);
    res.send(JSON.parse(body.text()));
  } catch(e) {
    console.error(e);
    res.status(500).send('Ocorreu um erro interno.');
  }
});

app.listen(3000, () => console.log('A aplicação está sendo executada na porta 3000!'));

The installation of express in your application can be done by means of the command below:

npm install express

And the installation of the module node-fetch can be done by means of the command:

npm install node-fetch

The service can be accessed through:

http://localhost:3000/

Observing: Since you provided an image instead of the code, typos may occur. It is important that you do not put in your question the image of the code but the code itself, making it easier for those who may answer.

  • Thank you very much for answering. So, I think I didn’t express myself well, by "return" I meant taking the result of the scope of the function and treating it outside of it, but since I’m starting now with Ode, I don’t know if it’s good practice to do this, or if I’m even using it wrong. I want to do this to play the result for HTML/CSS later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.