fill variables with express middleware js

0

I'm trying to fill a variable with a middleware that receives information through a request json and I'm storing it in a global variable which I later use in a render with pug, but the first loads return an empty variable, How can I ensure that it is loaded prior to viewing? here is my code

function fillVars(req, res, next){
     var urlCandidates = "https://web.com/count_by?group=true";
    request({url: urlCandidates,json: true }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        jsonTwiteros = body;
        }
    });
    next();
}
// function to call render
function render(req, res, next){
    console.log("Ingreso a render");
    res.render('main',{total:jsonTwiteros } );
        next();
}
function  close(req, res, next){
    res.end();
}
//set route 
app.get('/',fillVars, render,close);
    
asked by Paul 20.01.2017 в 16:34
source

1 answer

0

When you create a middleware the next () means that the request can continue traveling. Basically your mistake is that the next one should be inside the callback of the request, because if you are not waiting for it to end to tell you, continue with your path.

I would recommend that the variable be added to the response, remember that the next () continues with the same response. Express has a variable within the response especially to perform these things.

This varialbe is called: locals. This is inside the response. You should do the following:

function fillVars(req, res, next){
    var urlCandidates = "https://web.com/count_by?group=true";

    //Ejecuto el request
    request({
        url: urlCandidates,
        json: true
    }, function (error, response, body) {
        //Guardo el body
        res.locals.jsonTwiteros = (!error && response.statusCode === 200) ? body : {};

        //Una vez que terino el request y guarde la respuesta continuo con el request
        next();
    });
}
// function to call render
function render(req, res, next){
    res.render('main',{
        total: res.locals.jsonTwiteros
    } );

    next();
}

function close(req, res, next){
    res.end();
}

app.get('/',fillVars, render,close);
    
answered by 20.01.2017 / 19:23
source