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);
});
Related
So playing around with node, thought I would write a straight forward news ticker to put on my very minimalistic node page, seemed like fun. The thing is, I keep on getting
RangeError: Maximum call stack size exceeded
But I can not for the life of me figure out where the error occurs.
Have thrown is some additional debug comments, even removed parts of almost every file, but it all comes down to the same thing. If I start the application it gets to listening on port 3000 without problems. If I try to access it, i get the error message above.
Here is the app.js code
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, stylus = require('stylus')
, nib = require('nib')
, mongo = require('mongodb')
, logger = require('express-logger')
, bodyParser = require('body-parser')
, methodOverride = require('express-method-override')
, errorhandler = require('errorhandler')
, monk = require('monk');
var app = express();
//Is this specifically for nib and stylus to work
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib())
}
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
//app.use(express.favicon());
//app.use(express.logger('dev'));
//app.use(express.bodyParser());
//app.use(express.methodOverride());
app.use(app.router);
app.use(stylus.middleware(
{ src: __dirname + '/public'
, compile: compile
}
));
app.use(express.static(path.join(__dirname, 'public')));
//development only
//if ('development' === app.get('env')) {
//app.use(express.errorHandler());
//}
//Lets do some stuff to get info from the database
var db = monk('localhost:27017/meetallnews');
var router = express.Router();
//Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Also, the routes/index.js
console.log('Called index.routes');
var express = require('express');
var router = express.Router();
exports.index = function(req, res){
console.log('render page');
res.render('index', { title: 'Meet All' });
};
//This is to read from the database
router.get('/userlist', function(req, res) {
console.log('Called database');
var db = req.db;
var collection = db.get('sitenews');
collection.find({},{},function(e,docs){
res.render('newslist', {
"newslist" : docs
});
});
});
Any suggestions welcome, even where to start looking. I removed the whole route.get section above, and still got the same (or an identical) error. Tried to remove stuff from the jade file, to the extent where there was only the header line left, still the same error message. And always after the server have reached end of app.js (have said Server on port 3000)
Thank you very much lukaszfiszer and Mr Pomax.
Turns out that the error message was a bit misleading, making me think it was some kind of eternal loop or some strange stuff from the database.
It was because I am a horrible thief and stole some code from somewhere for the routes, and missing to remove the line app.use(app.router); when also having routes = require('./routes')
Once that was removed I got a brand new error that I understand where it comes from and what it is (and not really related to this issue, only proves that untested coded must be tested.
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.
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());
I have this simple node.js static file server:
var express = require('express');
var app = express();
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: "secret" }));
app.use(express.static(process.env.OPENSHIFT_REPO_DIR + '/public' ));
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
app.listen(port, ipaddress);
When I publish to OpenShift (no errors in the terminal) and navigate to the site, I see Cannot GET /
I have index.html in my public folder, along with some css and JavaScript.
Any idea what I'm doing wrong?
Here it is: Hey, did you make sure to commit the public folder?
You need the load the routes.
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
You are also not loading any views.
Here's the documentation of express: http://expressjs.com/guide.html
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}));