-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.

3
  • req.body.hasOwnProperty('name') is one of the options!
    – Ram
    Aug 29, 2016 at 7:35
  • @Vohuman my question is different, it's related to form data, not some random javascript object Aug 29, 2016 at 7:51
  • req.body is an object. A regular/plain object.
    – Ram
    Aug 29, 2016 at 8:01

1 Answer 1

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;
}
1
  • @Vohuman - How does it not? He wanted a way to check post params. Aug 29, 2016 at 7:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.