how to print the data from post request on console - node.js

I am trying to print the post data on my console
app.js
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 7002);
app.use(express.static(__dirname + '/public/images'));
app.post('/Details/',function(request,response,next){
app.use(express.bodyParser());
var keyName=request.query.Key;
console.log(keyName);
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Initial snapshot::
I test with POST-MAN with below data::
Now i get error as::
I just want to print the data i recieved from postman that is dev
..... which is being displayed as undefined ?
How to resolve this !
[Edit] ---- Adding body parser outside the route
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 7002);
app.use(express.static(__dirname + '/public/images'));
app.use(express.bodyParser());
app.post('/Details/',function(request,response,next){
var keyName=request.query.Key;
console.log(keyName);
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Still have same error

Instead of query:
var keyName=request.query.Key;
console.log(keyName);
use body:
var keyName1=request.body.key;
console.log(keyName1);
Code:
var express = require('express')
, async = require('async')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 7002);
app.use(express.static(__dirname + '/public/images'));
app.use(express.bodyParser());
app.post('/Details/',function(request,response,next){
var keyName1=request.body.key;
console.log(keyName1);
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/post/', function(req, res) {
// print to console
console.log(req.body);
// just call res.end(), or show as string on web
res.send(JSON.stringify(req.body, null, 4));
});
app.listen(7002);

Use request.query when you have querystring params.
For form/post data use req.body.
In your case, use request.body.key.

An update on using the middleware, body-parser, for later versions of Express: Using app.use(express.bodyParser()) will report an error such as:
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
This can be addressed by first installing the body-parser middleware:
npm install body-parser
then write code such as:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
and then accessing the body of the request object, for example, console.log(req.body)

You can't call app.use(express.bodyParser()); inside middleware/route handler:
request should pass through bodyParser() before it reaches route handler
you will be adding new bodyParser()s in each request, but they will be after app.router and will never work

Use built in function "util" to print any type of json data in express js
var util = require("util");
console.log(util.inspect(myObject, {showHidden: false, depth: null}));

Related

Node Js saving to a txt file not working

I have a server running on Node Js. What I'm doing is whenever the users submit something to save their input to a text file. When I run my server as a localhost it works and saves the input to the file. Whenever I run it on the real published server it doesn't. Is there a way to accomplish it on the real server without a database?
My code:
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8081;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + '/public'));
app.use('/images', express.static(__dirname +'/images'));
app.get('/', function(req, res){
res.sendFile('main.html');
});
app.listen(port, function(){
console.log('Server is running on port:' + port);
});
app.post('/submit', function(req, res){
var data = fs.writeFileSync('fileSync', req.body.rank, 'utf8');
return res.sendFile('success.html');
});
Thank you in advance!

NodeJS express SOAP

I'm consuming a soap request with express and bodyparser, however the request is not properly formatted on consumption i.e the first equals (=) sign is converted to colon (:) i.e
Below is my code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
require('body-parser-xml')(bodyParser);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.xml());
app.get('/',function(req,res){
res.send("hello");
});
app.post('/soap',function(req,res){
req.setEncoding('utf8');
var request = req.body;
console.log(request);
res.end("yes");
});
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
Got the answer, the client was sending the data using incorrect (text) content type. With postman, ensure you set content type to text/xml or application/xml.

Access the public folder when using node and Express?

I have looked through stackoverflow and read the express documentation, I can't figure out why the app won't run when I implement "app.use(express.static());" does anyone know a fix?
var express = require('express')();
var app = require('express')();
var server = require('http').Server(app);
var io = require("socket.io").listen(server);
//If i use this my app will not start
// app.use(express.static());
app.get('/', function(req, res){
res.sendfile('index.html');
});
//Get input from front-end
io.on('connection', function(socket){
// On input do something
socket.on('directional in', function(unique_id, input, input1){
// send info to index
io.emit('directional out', unique_id, input, input1);
});
});
server.listen(3000, function(){
// Server is running
console.log('listening on *:3000');
});
Any help would be great!
You're not initialising express correctly. The correct way would be as follows:
var express = require('express');
var app = express();
With this, you will be able to do
app.use(express.static(__dirname + '/public'));
All together, a fully functional express app would look like this in its most basic form:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 3000);
Let me know what happens.

No response from simple Expressjs app

I'm struggling a bit upgrading to expressjs 4.0. The very simple code below hangs requests to http://localhost:3000/ and no amount of rearranging things fixes that. However, if I comment out the app.use() statements for cookie-parser, body-parser and express-session it works. Obviously I need them so leaving them commented out is not an option.
I know I'm doing something wrong that's very simple but I am not able to see it. Can someone give me a nudge in the right direction?
var express = require('express')
, cookie = require('cookie-parser')
, body = require('body-parser')
, session = require('express-session')
, http = require('http');
var app = express();
var router = express.Router();
app.use(cookie);
app.use(body);
app.use(session({ secret: 'bigsecret' }));
router.get('/', function(req, res, next) {
res.send('Welcome');
});
app.use(router);
app.set('port', process.env.PORT || 3000);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The middleware should be passed as function invocations:
app.use(cookie);
app.use(body);
should be
app.use(cookie());
app.use(body());

Cannot read post parameters with Node.js and Express framework

I have a node.js server with express Framework.
var express = require('express');
var http = require('http');
var api_helper = require('./helpers/api_helper');
var app = express();
app.use(app.router);
app.use(express.bodyParser());
app.set('port', process.env.PORT || 8081);
app.post('/api/nodev1/users/login', function(req, res){
var email = req.param('email', null);
var password = req.param('password', null);
console.log(email);console.log(password);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
When I try to post a request to /api/nodev1/users/login I cannot read the parameters. I am trying with curl as follows:
curl -d "email=user#example2.com" -d "password=mypassword" http://localhost:8081/api/nodev1/users/login
The email and password are undefined.
You have to move app.use(app.router) below app.use(express.bodyParser()). app.router is just a hook in which stage to handle your routes. And if it comes before bodyParser the body is not parsed.
Your code could look like this (in case I didn't manage to explain understandable):
var app = express();
app.use(express.bodyParser());
app.set('port', process.env.PORT || 8081);
app.use(app.router);
// I added following line so you can better see what happens
app.use(express.logger('dev'));
app.post('/api/nodev1/users/login', function(req, res){ ... }
Offtopic remark: express.bodyParser() should only be used when you have file-uploads. And then you have to take care of deleting temp-files. If you don't have file-uploads, you are better off with only
app.use(express.json());
app.use(express.urlencoded());
I just wanted to add this in case you didn't know. I ran in problems because I didn't know...
Edit for Express 4
Thanks to #jonathan-ong there is no app.use(app.router) since Express 4:
All routing methods will be added in the order in which they appear. You should not do app.use(app.router). This eliminates the most common issue with Express.
In other words, mixing app.use() and app[VERB]() will work exactly in the order in which they are called.
Read more: New features in 4.x.
edit - nope, see other answer about middleware order!
change req.param to req.body.x:
app.post('/api/nodev1/users/login', function(req, res){
var email = req.param('email', null);
var password = req.param('password', null);
console.log(email);console.log(password);
});
to
app.post('/api/nodev1/users/login', function(req, res){
var email = req.body.email);
var password = req.body.password);
console.log(email); console.log(password);
});

Resources