简体   繁体   中英

Javascript REST API not processing correct values

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=test@test.com&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?

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

PARAMS test@test.com, 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 eg

{
  "firstName": "my",
  "secondName": "Name",
  "email": "test@test.com",
  "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.' }); }); } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM