1

Hello I am new to NodeJs. Currently I am working in node with Express framework. I installed the express-back package in my project and now I want to send send back data to view from where post request fired. Below is my code that I write:

routes.js

router.post('/register/user',Rules.UserRules.registerUser,UserController.registerUser)

UserController.js

const {check, validationResult} = require('express-validator');
registerUser = function (req, res, next) {

    // Validate request parameters, queries using express-validator
    const errors = validationResult(req)
    console.log("==== errors ===")
    console.log(errors.array())
    if (!errors.isEmpty()) {
        console.log("==== erorror founded ====")
        return res.redirect('/signup',{errors:errors})
    }else{
        console.log('--- form body ----')
        console.log(req.body)
    }

}
module.exports = {registerUser}

When I submit my form to this route then control moves to UserController and I validations fails then I want to send it back to view without defining the redirect path I just want to send it back to view from where request received with errors. But I did not find any useful solution yet. Is there any idea that how I can achieve this target. Suggest any useful link for nodejs beginner.

Rizwan Saleem
  • 904
  • 11
  • 28

1 Answers1

0

use res.send(errors) it send errors to client at this route. but if you want to redirect it to another route and then send it to client you have to create /signup route and use res.send(errors) it send errors to client. by default ``` res```` will redirect to redirected route.

router.post('/signup', (req, res)=>{
//send error or do somethings.
res.json(req.body.errors);
})