2
var express = require('express');
var mysql=require('mysql');
var bodyParser = require('body-parser');

var con=mysql.createConnection({
    host:"localhost",
    user:"root",
    password:"",
    database:"nodedb"
});

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


app.post('/reg', function (req, res) {     
    var name=req.body.user_name;
    console.log(name);

    con.query("SELECT * FROM users WHERE email = ?", [req.body.email],
    function(err,result){       
            if(result.length > 0){
            console.log('mail already exist');
            res.json('mail already exist');

            }
        else{
  con.query("INSERT INTO users (`name`,`email`,`contact`,`password`) VALUES (?,?,?,?) ",  [req.body.user_name,req.body.email,req.body.contact_no, req.body.user_password],
    function(err1,result1){
        if(err1){

        console.log('failed');  
        res.json(err1);
        }
        else{
            console.log('1 recoed inserted');   
            res.json(result1);

        }

 })
        }
})
}

req.body.user_name print undefined in console and null on postman. It is working on web page but not on postman. What should i do now. I looked in many websites but i didn't get answer.

Devesh Joshi
  • 21
  • 1
  • 3

3 Answers3

4

You need to select the correct header content type: x-www-form-urlencoded

enter image description here

Hope it helps.

Zeeshan Tariq
  • 604
  • 5
  • 10
3

In the body of postman, make sure you are using raw and make the Application type to Application/json, then you can mention

{
  "user_name": "Your_name"    
}

enter image description here

Mr.Bhat
  • 397
  • 5
  • 15
3

You might not have initialized the middleware for using the body parser. Here's how you can do it:

Put app.use(express.json()); in the entry point of your project.