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

*爱你&永不变心* 提交于 2019-12-25 03:36:25

问题


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());

回答1:


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"
  }



回答2:


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'}
});



回答3:


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 !



来源:https://stackoverflow.com/questions/32810728/i-cant-get-values-from-req-body-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!