1

I am trying to add a unique ID to my req.session but when the function executes if I want to go to another page it timeout due to infinite loading. Is there a way to do this correctly?

app.use(function (req, res, next) {
    if (req.query.inv) {
        sql.query(`SELECT * FROM inv WHERE inv='${req.query.inv}';`, (error, result) => {
            if(error) console.log(error);
            if(result.length < 1) {
                req.session.inv= '';
                next()
            } else {
                req.session.inv = `?inv=${req.query.inv}`;
                console.log(req.session.inv);
                next()
            }
        });
    } else {
        if(!req.session.inv) {
            req.session.inv= '';
            next()
        }
    }
});

1 Answers1

0

You have a middleware which must call next() when complete so that the next middleware in the stack can be called. See Express's Using middleware documentation.

Take a look at your logic - if inv is not in your query string but does exist in your session, then next() is never called. This aligns with the issue you are having - you add inv to your session, and then on your next page load you will be forever stuck in your middleware. You would instead want logic like this:

app.use(function (req, res, next) {
    if (req.query.inv) {
        /* .... */
    } else if (!req.session.inv) {
        req.session.inv= '';
    }

    next(); // this makes sure that next() always gets called
});

You also have a glaring SQL Injection risk because you are taking a raw query string value and passing it directly into your query. What you want is a parameterized query - I linked to node-postgres documentation even though I'm not sure what database you are actually using. As of now your query is not safe.

Jason Roman
  • 8,146
  • 10
  • 35
  • 40
  • Thank you for your reply it worked for me, the only thing I am asking now is how can I make my SQL Query safe? PS. Using MySQL. – Omar Fakhoury Apr 30 '20 at 07:09
  • You can take a look at the answer here for help with that, it explains everything very well https://stackoverflow.com/a/41172686/1307183 – Jason Roman Apr 30 '20 at 08:16