0
votes

I have built a JavaScript Server Authentication API, but am facing some issues. When I pushed this POST request using Postman:

http://localhost:3000/signup?firstName=my&secondName=Name&[email protected]&password=password

The router triggers this function:

app.post("/signup", Auth.userExist, function (req, res, next) {
     if (!req.body.email || !req.body.password) {
            res.json({success: false, msg: 'Please pass email and password.'});
        } else {
            var newUser = new User({
            firstName: req.body.firstName,
            lasttName: req.body.lastName,
            email: req.body.email,
            password: req.body.password
            });
            // save the user
            newUser.save(function(err) {
            if (err) {
                return res.json({success: false, msg: 'Username already exists.'});
            }
            res.json({success: true, msg: 'Successful created new user.'});
            });
        }
    });

The please pass email and password error is firing, I can't see why this would be happening?

1
try req.query this should check query string params - user2950720
Did you do a console.log(req) and examine what's in there? This is elementary debugging. Also, are you running middleware that processes the query string? node.js does not parse the query string automatically without the appropriate middleware to do it. - jfriend00
@user2950720 Do you mean like instead of my if (!req.body.email etc., I use if {!req.query){ ? If so, that sill produces the same outcome - George Edwards
what is inside Auth.userExist - user2950720
Well, you are POSTing the params as a query string. Try adding them to the body of the request. - Johannes Jander

1 Answers

0
votes

using this I am able to get past the error as you are sending a query string you need to use req.query

PARAMS [email protected], password

If you want to use req.body you need to send the parameters not in the query string but in the body of the request e.g

{
  "firstName": "my",
  "secondName": "Name",
  "email": "[email protected]",
  "password": "password"
}

app.post("/signup", function(req, res, next) {
  if (!req.query.email || !req.query.password) {
    res.json({
      success: false,
      msg: 'Please pass email and password.'
    });
  } else {
    var newUser = new User({
      firstName: req.query.firstName,
      lasttName: req.query.lastName,
      email: req.query.email,
      password: req.query.password
    });
    // save the user
    newUser.save(function(err) {
      if (err) {
        return res.json({
          success: false,
          msg: 'Username already exists.'
        });
      }
      res.json({
        success: true,
        msg: 'Successful created new user.'
      });
    });
  }
});