-3

Suppose I want to see an input, say name is set in a form in php, I can do this:

if (isset($_POST['name']) {
    echo("type in name"); # or something
}

Can I do something like that in nodejs this way:

router.get('/', function (req, res, next) {
    if (req.body.name == "") {
        res.send('type in name'); // or something
    }
});

I'm new to both php and nodejs, so can someone clarify this for me, or provide me with a better/correct solution in nodejs?

I don't want to check if some object has some property, but if the form submitted has the property name set, i.e name is non empty.

user3248186
  • 1,518
  • 4
  • 21
  • 34

1 Answers1

1

To get post data, you need to use body-parser.

Then you need a route handler for handling the post data.

router.post('/', function (req, res, next) {
    // if you set up body parser correctly, all your form data will be accessible in `req.body`
    console.log(req.body) ; 

    const errors = validate(req);

    if(errors.length) {
        // show errors

        return;
    }

    // do something with form data.
});

function validate(req) {
    const errors  = [];

    if (! req.body.firstName) {
        errors.push('First name is required');
    }

    // do the same for all input fields

    return errors;
}
Swaraj Giri
  • 4,007
  • 2
  • 27
  • 44