How to get post params in app.post

617 views Asked by At

I am developing nodejs project. Where I am using ejs with the help of express-helpers module to generate view template html.

in server.js file I have written below code

var http = require('http');
var path = require('path');

var async = require('async');
var socketio = require('socket.io');
var express = require('express');


var app = express();

var helpers = require('express-helpers')
helpers(app);

var server = http.Server(app);

server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
  var addr = server.address();
  console.log("Chat server listening at", addr.address + ":" + addr.port);
});

app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));

// respond with "index.html" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.render('index.html');
});

app.get('/demo', function (req, res) {
  res.render('demo.ejs');
});

app.post('/demo', function (req, res) {
      console.log(res.body)
}); 

I want to know that in app.post how should id get post params

app.post('/demo', function (req, res) {
      console.log(res.body)
}); 

I have tried console.log(req.body) but giving as undefined Also tried console.log(res.body) but giving as undefined

Let me know how should I implement it?

2

There are 2 answers

0
Jinceon On BEST ANSWER

you should use a middleware such as body-parser

var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.post('/demo', function (req, res) {
  console.log(req.body)
}); 
0
Bidhan On

Use the body-parser middleware. First, you need to install it using npm install body-parser. And then use it in your application like this

var bodyParser = require('body-parser');
.....

// For Content-Type application/json
app.use(bodyParser.json()); 
// For x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true })); 

....

app.post('/demo', function (req, res) {
  console.log(req.body);
});