0

I've got this code to make a request to an API

var request = require('request');


 request('http://www.google.com', function (error, response, body) {
 console.log('error:', error); // Print the error if one occurred
 console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
 console.log('body:', body); // Print the HTML for the Google homepage.
    });

However, I also a route to serve in my node app and the response I get is out of scope in the route. I want to add the values from my request into view using EJS but with EJS i have to define the values to be used by the file in the .render() and getting those values just seems to not be possible.

My app.js looks like this

const express = require('express');
var request = require('request');
const path = require('path');
const chalk = require('chalk');

const app = express();
const port = process.env.PORT || 3000; // Port number

// var url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL

app.use(express.static(path.join(__dirname, '/public/')));
app.use('/css', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/jquery/dist')));
app.set('views', './views');
app.set('view engine', 'ejs');


function apiCall(callback) {
  request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var result = JSON.parse(body);
      // console.log(result);
      return callback(result, false);
    } else {
      return callback(null, error);;
    }
  });
}

app.get('/', (req, res) => {
  const url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL

  const x = request(url, function (error, response, body){
  const result = JSON.parse(x.body);
  console.log(result);

  });
  res.render('index',{
      //temp: data.list[0].main.temp,
      place : result.city['name'] // || data.city['name'],
      //wind: data.list[0].wind.speed,
      //desc: data.list[0].weather[0].description,
      }
    );
    });

app.listen(port, () => {
  console.log(`listening on port ${chalk.green(port)}`);
});

any help would be really appreciated!

  • 2
    Why not just move the `res.render` inside the `request` callback? – tymeJV Aug 14 '18 at 20:48
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Aug 14 '18 at 20:54
  • @tymeJV how would that look? – Madalitso Phiri Aug 14 '18 at 21:00

1 Answers1

1

const request = require('request');
const express = require('express');
const path = require('path');
const chalk = require('chalk');

const app = express();
const port = process.env.PORT || 3000; // Port number

app.use(express.static(path.join(__dirname, '/public/')));
app.use('/css', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/jquery/dist')));
app.set('views', './views');
app.set('view engine', 'ejs');


function apiCall(url, callback) {
  request(url, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      var result = JSON.parse(body);
      // console.log(result);
      return callback(null, result);
    } else {
      return callback(error, null);;
    }
  });
}

app.get('/', (req, res) => {
  const url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL

  apiCall(url, (err, body) => {
 if(err) {
     // handle error
      return;
    }
    res.render('index', {
      //temp: data.list[0].main.temp,
      place: body.city['name'] // || data.city['name'],
      //wind: data.list[0].wind.speed,
      //desc: data.list[0].weather[0].description,
    });
  });

})


app.listen(port, () => {
  console.log(`listening on port ${chalk.green(port)}`);
});

if you are trying to render after the api call is finished.

Aadhi Vive
  • 575
  • 1
  • 5
  • 17