Anwesa Roy
Anwesa Roy

Reputation: 33

How to send a data from req.body using nodejs

How can I send data from body using nodejs?

I am writing a code in node.js in which the user inputs a data in the body. And based on that input, the program fetches the data from the database and displays it in JSON format.

I have written the following code:

 app.post('/city', (req,res) => {

    var id = parseInt(req.body.id);
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query(`SELECT * FROM city WHERE state_id=${id}`, function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             res.status(200).send(result.rows);
        })
    })  

});

I feel that something is wrong with var id = parseInt(req.body.id);. Because, when I am running the code, it says it is not able to recognize the id?

Also, when I run this in Postman, I get the following error:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>TypeError: Cannot read property &#39;id&#39; of undefined
            <br> &nbsp; &nbsp;at app.post (F:\DatabaseProject15\routes\common.js:36:32)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at next (F:\DatabaseProject15\node_modules\express\lib\router\route.js:137:13)
            <br> &nbsp; &nbsp;at Route.dispatch (F:\DatabaseProject15\node_modules\express\lib\router\route.js:112:3)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
            <br> &nbsp; &nbsp;at F:\DatabaseProject15\node_modules\express\lib\router\index.js:281:22
            <br> &nbsp; &nbsp;at Function.process_params (F:\DatabaseProject15\node_modules\express\lib\router\index.js:335:12)
            <br> &nbsp; &nbsp;at next (F:\DatabaseProject15\node_modules\express\lib\router\index.js:275:10)
            <br> &nbsp; &nbsp;at expressInit (F:\DatabaseProject15\node_modules\express\lib\middleware\init.js:40:5)
            <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
        </pre>
    </body>
</html>

Details:

var id = parseInt(req.body.id);

is at F:\DatabaseProject15\routes\common.js:36:32

Error at console:

TypeError: Cannot read property 'id' of undefined
    at app.post (F:\DatabaseProject15\routes\common.js:36:32)
    at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\DatabaseProject15\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\DatabaseProject15\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)
    at F:\DatabaseProject15\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\DatabaseProject15\node_modules\express\lib\router\index.js:335:12)
    at next (F:\DatabaseProject15\node_modules\express\lib\router\index.js:275:10)
    at expressInit (F:\DatabaseProject15\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (F:\DatabaseProject15\node_modules\express\lib\router\layer.js:95:5)

CODE:

app.js

const pg        = require('pg');
const express   = require('express');
const app       = express();

var common = require('./routes/common')
app.use('/common', common)


app.listen(4600, function () {
    console.log('Server is running.. on Port 8000');
});

router/common.js

const pg        = require('pg');
const express   = require('express');
const app       = express();


const config = {
    user: 'postgres',
    database: 'mydb',
    host: '40.83.121.72',
    password: 'abc',
    port: 5432
};

const pool = new pg.Pool(config);


app.post('/', (req, res, next) => {
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query('SELECT * FROM city', function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }

             res.status(200).send(result.rows);
        })
    })
 });

 app.post('/city', (req,res) => {
    //var id = parseInt(req.params.id);
    var id = parseInt(req.body.id);
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query(`SELECT * FROM city WHERE state_id=${id}`, function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             res.status(200).send(result.rows);
        })
    })  

});

app.post('/app/state/:id', (req,res) => {

    var id = parseInt(req.params.id);

    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query(`SELECT * FROM state WHERE id=${id}`, function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             res.status(200).send(result.rows);
        })
    })  

});

module.exports = app

Upvotes: 0

Views: 387

Answers (1)

Asaf Aviv
Asaf Aviv

Reputation: 11770

In app.js above your routes add

app.use(express.json());

this will let you parse application/json, if you need to parse application/x-www-form-urlencoded you need to add

app.use(express.urlencoded({ extended: true }));

Upvotes: 1

Related Questions