简体   繁体   中英

I can't get values from req.body node.js

I need help with node.js: I have my req.body populated like this

{ 
   '{
       "email":"mail@hostname.com",
       "password":"12345"
    }'
     : '' 
} 

but I can't get values req.body.email and req.body.password are undefined

My code is:

user.js

exports.loginByEmail= function(req, res) {
console.log('POST');
console.log(req.body);//show values
console.log(req.body.email);//undefined
console.log(req.body.password);//undefined
    User.find({email:req.body.email,password:req.body.password}).toArray(function(err, userLoged) {
    if(err) return res.send(500, err.message);
    res.status(200).jsonp(userLoged);
    });
};

app.js

var express = require("express"),
app = express(),
bodyParser  = require("body-parser"),
methodOverride = require("method-override");
mongoose = require('mongoose');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());

The way you have the body set up in the first bit, it looks like the key is your object string and the value is an empty string.

ie your body is the key '{email:mail@hostname.com,password:12345}' (quotes removed for clarity) with the value ''

Try writing your body as

  {
    email: "email@email.com",
    password: "12345"
  }

Try (on the client side):

$http({
    method: 'POST',
    url: 'http://localhost:3000/api/loginByEmail',
    data: 'email=' + encodeURIComponent(this.formLoginByEmail.username) +
          '&password=' + encodeURIComponent(this.formLoginByEmail.password),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

If you can not get data by using req.body.email and req.body.password then you should use req.query.email and req.query.password . This should return the data sent in a query and in this case the query was through POST method.

Hope it works !

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