user3012847
user3012847

Reputation: 51

Checking pass field in post data [NodeJS]

I'm having a problem passing post data in node js. I already know how this works but i don't know how to validate the fields in the post data.

Example:

If I pass the json {"userInfo":"myusername"} my server accepts it. But if I pass a json with invalid format like this {"usersInfo":"myusername"} my server is crashing. My goal is before receiving the data i need to check the fields if it is valid and if not I will send a 400 Bad Request status code res.writeHead(400);

    app.post('/api/adduser', function(req, res) {

         var userInfo = req.body.userInfo;

         //code goes here

    });

Is there any way on how to do this? Thanks guys.

Upvotes: 0

Views: 360

Answers (2)

Lee Jenkins
Lee Jenkins

Reputation: 2470

At a minimum you ought to check to see if req.body.userInfo is defined.

app.post('/api/adduser', function(req, res) {
     if( typeof req.body.userInfo === "undefined" ) {
         // error code here
     } else {
         // add-user code goes here
     }
});

I would advise against using userInfo == undefined because you're just creating a crack for bugs to crawl in. Don't go there.

A more robust solution would be to use a validation module. There are a few different validators for node.js. What you choose will depend on your tastes and what framework you're using (express, restify, etc.). A validator is really beyond the scope of your original question, but you know, FYI.

Upvotes: 1

Jonathan M. Hethey
Jonathan M. Hethey

Reputation: 714

If your key could be named differently you could check for it being undefined:

if(userInfo == undefined){
    res.writeHead(400)
}

Upvotes: 0

Related Questions