George Edwards George Edwards - 6 months ago 24
Javascript Question

POST API body values coming through undefined?

I am building up an API on the MEAN stack, using mongoose. The API should handle user signup and authentication. To test this, I am using the chrome extension, postman to submit post requests to

/signup
.

app.use("/signup", bodyParser.urlencoded({ extended: false }));
app.post("/signup", Auth.userExist, function (req, res, next) {
if (!req.body.email || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
console.log("email: " + req.body.email);
console.log("password: " + req.body.password);
} else {
//do create new user logic...
res.json({success: true, msg: 'Successful created new user.'});
}
});


Here you can see what I am sending in the body of my request to the API:

Postman

in the console, I am getting this:


TypeError: Cannot read property 'email' of undefined


Why is the body of my request not getting through?

Answer

In POSTMAN select x-www-form-urlencodedinstead of form and then pass the form values. Your code should work fine.