Sunday, 2 April 2017

Using a POST request inside a GET request's call back (Closures)

I will demonstrate my problem with this simplified code:

app.get('/test', (req, res) => {
    let x = req.query.someVar;
    app.post('/test', (req, res) => {
        console.log(x);
    });
    res.send(`Hello ${req.query.someVar}`);
});

The first time this code runs, the POST callback function saves a reference to x which is whatever I pass as query parameters. if I change the query parameters, send another GET request it will be updated in the server's response i.e.res.send(Hello ${req.query.someVar}); but a POST request will still log the original x value to the console.

Why is it behaving this way? I have tried many things like passing by objects and through other functions, etc..

I am familiar with how closures work, but obviously not entirely as this is most definitely a problem with the POST call back preserving the value of the query parameters and not updating them.

Thanks.



via JohnSnow

No comments:

Post a Comment