Andres Vera
Andres Vera

Reputation: 72

Node and Express send json

How can I pass the json (posiciones) that is in the request, to the res.render to send it to the index (my view), everything works until the console, but when it arrives at the res.render it marks me error of: positions not it is defined

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cons = require('consolidate');
var dust = require('dustjs-helpers');
var app = express();
const request = require('request');
var port = process.env.PORT || 3001;

app.engine('dust', cons.dust);

app.set('view engine', 'dust');
app.set('views', __dirname + '/views');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));

const options = {  
  url: 'http://xx.xx.xx.xx:xxxx/api/positions',
  method: 'GET',
  headers: {
     'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxx',
     'Accept': 'application/json',
     'Content-Type': 'application/json',
 }
};

app.get("/index", function(req, res)  { 
request(options, function(err, response, body) {  
    var posiciones = JSON.parse(body);
    console.log(posiciones);
    res.json(posiciones);
  });
 res.render('index', {devices: posiciones});
});

app.listen(port, function(){
 console.log('servidor iniciado en http://localhost:' + port);
});

Upvotes: 0

Views: 243

Answers (1)

aquaman
aquaman

Reputation: 1658

It is because your request call is asynchronous. Till the time your request callback gets executed, your code has already tried rendering index. That is why it is giving error.

Render your index page inside callback -

app.get("/index", function(req, res)  { 
request(options, function(err, response, body) {  
    var posiciones = JSON.parse(body);
    console.log(posiciones);
    res.render('index', {devices: posiciones});
  });
});

Upvotes: 3

Related Questions