“How to resolve req.body undefined in Node JS ”

54
May 06, 2019, at 12:10 PM

I am setting up a node js server and in my output of req.body i keep getting undefined, i am trying to requesting SQL data from a form Get request

I am able to retrieve other queries just none involving req.body

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.static(__dirname + '/public'));
app.get('/submit',urlencodedParser,function (req, res){
connection.connect(function (err) {
if (err) throw err;
console.log(req.body.lname);
var exist = req.body.lname;
var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";
connection.query(sql, function(err,result) {
if (err) throw err;
console.log(result);
console.log(exist);
console.log(req.body.lname);
console.log("hello");
console.log(result);
});
});

'

output:

undefined [] undefined undefined hello []

Answer 1

Get request doesn't carry the req.body object.

You will have to use either req.query or req.params to pass your data or transform your get into post.

app.post('/submit', function(req, res) {
  connection.connect(function (err) {
    if (err) throw err;
    var exist = req.body.lname;
    var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";
    connection.query(sql, function(err,result) {
        if (err) throw err;
        else console.log(result);
    });
});
READ ALSO
How to improve speed when creating a DOM object with JSDOM with large (~30+ MBs) html files

How to improve speed when creating a DOM object with JSDOM with large (~30+ MBs) html files

I'm creating a tool that reads through an html file with two embedded XML files in columns, and pulls out elements based on styling properties (they are diffs that have various diffs highlighted in different colours) with Nodejs

57
Firebase Auth verify JWT ID Tokens without SDK with NodeJS

Firebase Auth verify JWT ID Tokens without SDK with NodeJS

Using NodeJS, how can I verify the JWT (idToken) provided by Firebase Auth, without Firebase Admin SDK?

49
How can I save ImageData as a PNG in Electron

How can I save ImageData as a PNG in Electron

In the browser, I was building an array of image data and as you can see here, converted it to quite a few different forms in order to download it in the browser, which worked:

41
Failing to Run Migrations At AWS RDS Database From Gitlab CI/CD

Failing to Run Migrations At AWS RDS Database From Gitlab CI/CD

I made a CI/CD pipeline to automatizate the deploy into the AWS Lambda and RDSAlso, create migrations using Knex Migrations, with NodeJS, to update this database

46