0

I am not able to get the post parameters in my node js ,when I put console it says undefined but when I post parameters from postman it is working.Can anyone suggest help, please?

exports.login = function( req, res ) {
console.log(req.body)
  var query = 'select * from profile where email = ? and password = ?'; 
 connection.query(query,[req.body.email,req.body.password],function(error,result,rows,fields){
    if(!!error){console.log(error)
      console.log('fail');
    }else{
      console.log(result);
      res.send(result);
    }
  // }

  });}

My Express code,

    var express = require('express')
  , cors = require('cors')
  , app = express(); 

var admin = require('../controller/user'); 
 router.post('/login',cors(), admin.login);
abdulbarik
  • 6,101
  • 5
  • 38
  • 59
MMR
  • 2,869
  • 13
  • 56
  • 110

2 Answers2

2

Always put body-parser before all route. Like this

  var app=express();
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));

Other wise always get undefined body value if you use it before any route since body not parsed yet.

abdulbarik
  • 6,101
  • 5
  • 38
  • 59
1

You forgot to use bodyParser. First install it using command

npm install body-parser --save

Then add the following to your app

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

After that you can use req.body

Rashad Ibrahimov
  • 3,279
  • 2
  • 18
  • 39
  • As I understand the first code is separate file, let's call it `Admin module`, and `admin.login` in the second code example refers to that file. So you have to use `body-parser` in `Admin module` file – Rashad Ibrahimov Sep 13 '16 at 08:10