0

I'm trying to display a result of a query using node.js express and pug. This is my node.js code

function test(req, res, next) {
    var result =  con.query("SELECT id FROM users WHERE email = '" + req.body.email + "'")
    return result;
}

router.post('/remind/submit', async (req, res, next) => {
    try {
        var result = await test(req);
        res.redirect('/login/remind', { success: result });
    }
    catch (error) {
         console.log(error);
    }
})

The problem is that what is displayed is an error in the console: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: { success: [Query] }

This is my pug form that sends the request.

form(method="post" action="/login/remind/submit" width="10%").flex-fill
      .form-group
        p Give us your e-mail address and we will send you a new password.
        p= success
      .form-group
        label E-mail
        input(type="text" name="email").form-control
      button(type=submit).btn.btn-primary Send

Right now i'm not displaying the response. Im trying to get it to work and redirect me correctly.

  • I tried to await the test(req) like so: ```router.post('/remind/submit', async (req, res, next) => { var result = await test(req); res.redirect('/login/remind', {success: result}); })``` I get the error in console and aplication hangs: UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: { success: [Query] } – Damian Kuberski Jan 08 '21 at 18:32
  • Right, `redirect` doesn't understand those parameters. See [this thread](https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context) for passing context with a redirect. But the async part appears correct now. – ggorlen Jan 08 '21 at 18:35
  • I looked at this thread, but i don't want to pass the result in a url, i just want to pass the object to pug. I tried to look on the internet on how to pass context with redirect but nothing i did had any effect, i still got the same error. Alse shouldn't the program stop if there is an error? Is the catch(error) not working? Why does the website hang and wait for the server if there was an error? – Damian Kuberski Jan 08 '21 at 20:20
  • The `try`/`catch` is in the `test` function so any error thrown in the route callback is uncaught. JS is allowed to throw errors in asynchronous functions and continue running on the main thread. The request will hang because a response was never sent. I'm not experienced with pug but I can look into it if you can show your require and middleware setup so I can reproduce your environment. Otherwise, that's sort of a separate problem than the original async issue, so maybe overhaul/edit your question accordingly since it has no answers. – ggorlen Jan 08 '21 at 20:26

0 Answers0