How to get post params in app.post - node.js

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?

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)
});

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);
});

Related

Express nodejs POST method return empty brackets

I can't get the value in my form. I am using a basic HTML form to send my data. When I try to test the return of the POST method in the console, I can't find the value of my input. This is my code:
let express = require('express');
let app = express();
// Moteur de template
app.set('view engine', 'ejs');
// Middleware
app.use('/assets', express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Routes
app.get('/', (request, response) => {
response.render('pages/index');
});
app.post('/', (req, res, next) => {
console.log(req.body);
});
app.listen(8080);
my console always return {}
Add this to the front of your code:
app.use(express.urlencoded({ extended : true}));
app.use(express.json());
body-parser is no longer needed, as this feature is already provided in express.js.
also I would suggest you to do const express = require('express'); const app = express(); instead of let express = require('express'); let app = express();.
Do npm install 'body-parser
Then update your code like this
let express = require('express');
let app = express();
// For FORM input
var bodyParser = require('body-parser');
// Moteur de template
app.set('view engine', 'ejs');
// Middleware
app.use('/assets', express.static('public'));
// Body parser For forms Actions
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Routes
app.get('/', (request, response) => {
response.render('pages/index');
});
app.post('/', (req, res, next) => {
console.log(req.body);
});
app.listen(8080);
This should fix it

Why is my NodeJS App not working as it should?

I don't understand what is my mistake but the app.Method are not really working.
server.js :
//express :
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
//middleware :
app.use(express.json);
app.use(bodyParser.urlencoded({ extended:false }))
//templating engine :
var ejs = require('ejs');
app.set('view engine', ejs);
//public directory :
app.use(express.static(__dirname + '/public'));
//pages:
app.get('/', function (req, res) {
console.log("Hello")
res.render('pages/index')
})
app.get('/post/new', function (req, res) {
res.render('pages/post-new')
})
app.post('post/new', function (err, req) {
console.log(req.body)
})
//listening
app.listen(8080, function (err, res) {
if (err) throw err;
else console.log(`Listening on 8080`)
});
I have my directory something like this:
node-modules
public
views
--pages
----index.ejs
----post-new.ejs
--partials
package-lock.json
package.json
server.js
I don't really understand why is it not working. I have tried adding console.log(req) in app.gets but they don't really log anything. And sorry for the dumb question.
EDIT: Answer is It is app.use(express.json()) NOT app.use(express.json)

Nodejs CANNOT GET

I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.
You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });
We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade

Nodejs shows Error "Cannot GET /test"

I am trying to retrieve output on other url / directory in nodejs but it's Display Error ("Cannot GET /test").
Please Suggest me what i have to do to get my output on ("http://localhost:8080/test").
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var session = require('express-session');
var cookieParser = require('cookie-parser');
app.set('view engine', 'pug');
app.set('views','./views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({secret: "Your secret key"}));
var Users = [];
app.get('/', function(req, res){
res.render('signup');
});
app.post('/signup', function(req, res){
if(!req.body.id || !req.body.password){
res.status("400");
res.send("Invalid details!");
} else {
Users.filter(function(user){
if(user.id === req.body.id){
res.render('signup', {
message: "User Already Exists! Login or choose another user id"});
}
});
var newUser = {id: req.body.id, password: req.body.password};
Users.push(newUser);
req.session.user = newUser;
res.redirect('/test');
}
});
app.listen(8080);
OutPut : Cannot GET /test
You did not specify a route for /test. You should have
app.get('/test', function(req, res, next){
res.render('test'); // This should have a view
});
Here i writing sample. create views folder in root folder and add one test.pub file to views then just run
Note:dont forget to install pug and express
var express = require('express')
var app = express()
app.set('view engine', 'pug');
app.set('views','./views');
// here am directly sending response without using view engine
app.get('/', function (req, res) {
res.send('hello world')
})
// here am sending response with using view engine
app.get('/test', function(req, res){
res.render('test');
});
app.listen(8000,function(){
console.log(" Server is running on port 8000");
});

App is Running But Not Opening in Browser? It shows Page Not Available

In console it shows message that app/server is running but when I open app in browser it show page not available.
Here's my code for the server initialization (app.js):
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var app = express();
var viewRoute = require('./routes/view'),
apiRoute = require('./routes/api');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', viewRoute);
app.use('/api', apiRoute);
server.listen(9190, function(){
var host = server.address().address,
port = server.address().port;
console.log("Server Running # http:%s:%s", host, port);
});
And my file with the routes (api.js):
var express = require('express');
var api = express.Router();
module.exports = (function() {
api.get('/', function(req, res, next) {
console.log("GET Request for Index Page");
});
api.get('/home', function(req, res, next) {
console.log("GET Request for Home Page");
});
return api;
})();
I've already searched google and every other resources but can't find solution.
It seems you are not sending response back to browser,
in api.js change api.get('/' code to like following:
api.get('/', function(req, res, next) {
res.send("Yes Its working now");
});
You're not sending anything back to the client, so nothing shows up in your browser. Use res.send or similar for this.
I'd suggest to change your code for something like this, and see if this works :
var express = require('express'),
app = exports = module.exports = express();
app.get('/', function (req,res) {
console.log("GET Request for Index Page");
res.send("GET / - 200");
});
app.get('/home', function (req,res) {
console.log("GET Request for home Page");
res.send("GET /home - 200");
});
I removed the exported function immediate call by the way.
I also had same issue, My server was running but i was not able to open my app on browser, Uninstalling skype worked for me.

Resources