0

I'm learning Node.js with Express. I'm doing some basic form validation. If it fails, I'd like to reload the page with same view showing the errors. For the validation I'm using express-validator.

I am able to display the errors and the same view, but the URL is not that one belonging to the view that has the form, but that one called by the POST request. I'd like to be redirected to the form view with the messages though.

This is my code so far

// process form to add ideas
app.post('/ideas', (req, res) => {

    req.checkBody('details', 'Details are required').notEmpty();

    var errors = req.validationErrors();

    if (errors) {

        res.render('ideas/add', {
            title: 'Add Ideas',
            errors: errors
        });

    } else {

        res.send('ok');

    }

});

So, even if I render back the view "ideas/add"... the URL is going to be "/ideas"... but I'd like it were "ideas/add" too.

Any ideas?

Thanks

rolfo85
  • 717
  • 3
  • 11
  • 27
  • if you need to change the url in browser, you are basically doing a url redirect. send a redirection to `/ideas/add` with extra infos e.g. error in query param. – gp. Dec 16 '17 at 10:29
  • Can you show me how? Cause I tried a few ways with res.redirect(“/ideas/add”); but I couldn’t figure out how to pass it the var errors. – rolfo85 Dec 16 '17 at 10:40
  • https://stackoverflow.com/questions/19035373/how-do-i-redirect-in-expressjs-while-passing-some-context#19038048 – gp. Dec 17 '17 at 05:36

0 Answers0