express server unresponsive after 5 POST's - node.js

I am using express to serve a single page webapp, and as a REST endpoint for said app. Everything works fine for the static page serving, but after 5 posts the server becomes unresponsive. I have seen a lot of other posts with this problem but they all say to just make sure to call res.send() or res.end() which i do in every call somewhere, regardless of how the logic branches. The app.js code is below.
/**
* Module dependencies.
*/
var express = require('express'),
http = require('http'),
path = require('path');
var app = express();
var auth = require("./controllers/authentication.js");
http.globalAgent.maxSockets = 100;
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
app.get('/public/*', function(req, res) {
res.sendfile('.'+req.url);
});
app.post('/auth/login', function(req, res, next) {
auth.login(req, res, next);
});
app.post('/auth/logout', function(req, res, next) {
auth.logout(req, res, next);
});
app.post('/auth/verify', function(req, res, next) {
auth.verify(req, res, next, function(req, res, next) {
res.conentType = 'json';
res.send(200, "authorized");
});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
and here is the command line output that i get (i tried issuing other requests after, but the server would not process them). I assume that I am somehow not terminating the connection properly, but cant figure out how.

problem was related to not closing mysql connection pool

Related

express - getting path of parrent router?

Lets say I want to have 2 different instances in "subfolders" in the url. In app js I have it defined like this:
var routes = require('./routes/index');
app.use('/myapp1', routes);
app.use('/myapp2', routes);
The inner routing would be the same.
But still in the router I want to "get" the path defined in the app.use - eg.: myapp1, myapp2
How do I get this in the router?
From routes/index.js:
router.use(/\/.*/, function (req, res, next) {
// want to see "myapp1/myapp2" without the *sub* path defined in this particular router eg.: /products /user etc.
next();
});
You might want to use the req.baseUrl property.
Example:
routes.get('/1', function(req, res) {
res.send([
req.baseUrl,
req.path,
req.baseUrl + req.path,
].join('\n'));
});
app.use('/api', routes);
Making an HTTP request to /api/1 would print:
/api
/1
/api/1
var express = require('express');
var app = express();
var router = express.Router();
app.use(function(req, res, next) {
req.appInstance = (req.url.indexOf('/app2/') == 0) ? 2 : 1;
next();
});
app.get('/', function(req, res, next) {
res.redirect('/app1/user');
});
router.get('/user', function(req, res, next) {
res.send(req.url +' on app' + req.appInstance);
});
app.use('/app1', router);
app.use('/app2', router);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

routing node.js and express

I'm having a problem routing in express 4. I was following the example, but it isn't loading. I'm just getting a spinning wheel.
How do you do routing in express version 4?
app.js:
var express = require('express');
var http = require('http');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
var port = (process.env.PORT || process.env.VCAP_APP_PORT || 5000);
app.use('/birds', require('./controller/bird'));
http.createServer(function (req, res) {
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end('Hello World!\n');
}).listen(port);
console.log('Server running at http://127.0.0.1:'+port);
bird.js:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
You're not calling the app.listen() function. Instead of the http.createServer one, you should invoke the Express function.
Please, take a look at a basic example.
Relevant code:
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Edit: as slebetman wrote in the comment, the more general way for it is:
http.createServer(app).listen(port, function(){
console.log('now listening on port ' + port);
});

Can't intercept 404 with express node js

This is my code:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.sendFile(__dirname + '/public/error.html');
});
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});
When I access the url http://localhost:3000/xyz, which does not exist, I get the standard page saying Cannot GET /xyz, instead of my custom error page. Why?
The function signature you're using (err, req, res, next) is for errors. E.g. a middleware calls next(new Error('failed')). What you need is a regular middleware which simply happens to be the last one that is executed, which means you interpret it as 404 (see answer below).
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.sendFile(__dirname + '/public/error.html');
});
//------------------
app.use(function(req, res, next) {
res.status(404);
res.sendFile(__dirname + '/public/error.html');
});
//------------------
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});
Node usually starts matching endpoints from top to bottom.
So first write down all the endpoints of your app, then write an endpoint like below at the end which will be executed when none of your defined endpoints match.
app.get('/path1', handler1);
app.get('/path2', handler2);
app.get('/path3', handler3);
app.get('/*',function (req, res) {
//This block will executed when user tries to access endpoint other than /path1,/path2,/path3
// Handle error here
})
Your code should look like this :
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.get('/*',function (req, res) { //If any of your defined endpoints doesn't match, this block will be executed.
res.status(404);
res.sendFile(__dirname + '/public/error.html');
});
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});

nodejs ExpressJs BackboneJs pushstate

I've got problemas with Backbone.history.start({pushState: true}); when is actived
I use the backbone router 'example/:id':'test' and the browser returns me an error
GET myhost:1337/example/js/views/test.js 404 (Not Found)
I want to rotate with Backbone for example myhost:1337/example/test without the necessity to request nodejs.
si, I dunno why,
Could be my server Nodejs?
Or Could be my code that it's not well written?
Thanks in advance
MY server code is
//var http = require('http');
var path = require('path'),
express = require('express'),
routes = require('./routes/index'),
http = require('http'),
app = require('express')();
app.configure(function(){
//app.set('view options',{layout: false });
app.set('port', process.env.PORT || 1337);
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the ned middleware (your error reporter)
app.use(function(err, req, res, next) {
if(!err) return next(); // you also need this line
console.log("error!!!");
res.send("error!!!");
});
});
app.get('*',function(req,res){
res.setHeader('content-type', 'text/javascript');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.redirect('http://localhost:1337#'+req.url);
});
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
This is something with your server. I'm willing to bet you didn't hold the shift key down when you typed out your route, so you have something like this in your server
app.get('example?:id':'test', function() {});
When you should have:
app.get('example/:id':'test', function() {});
This block:
app.post('/addPlace?:?',routes.addPlace);
app.get('/searchPlace?:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById?:id',routes.showPlaceById)
app.post('/deletePlace?:?',routes.deletePlace);
See the ?'s everywhere? This should really be:
app.post('/addPlace',routes.addPlace);
app.get('/searchPlace/:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById/:id',routes.showPlaceById)
app.post('/deletePlace',routes.deletePlace);
If you change that, /showPlaceById/:id will return what you expect.

express global middleware not being called

As far as I can tell I'm configuring my global middleware function as described in the docs and in every forum post on the subject, but it is not being called. Does anyone see what I'm doing wrong? express 3.2.5. In the log output I see the following:
Express server listening on port 9000
inside route
GET / 200 7ms - 2b
I expect to see "inside middleware", then "inside route". Instead, I just see "inside route".
The code:
var express = require('express'), http=require('http'), path=require('path');
var app = express();
app.enable('trust proxy');
app.set('port', process.env.PORT || 9000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('layout', 'layout');
app.use(require('express-ejs-layouts'));
app.use(express.favicon(__dirname + '/public/images/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride())
app.use(express.cookieParser('kfiwknks'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
} else {
app.use(function(err, req, res, next){
console.error (error);
res.send (500, "Internal server error");
});
}
app.use (function (req, res, next) {
console.log ("inside middleware");
next();
});
app.get ("/", function (req, res) {
console.log ("inside route");
res.send(200);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
This related post:
Express 3 error middleware not being called
is specific to error handling middleware. Mine is a vanilla middleware.
You should put your middleware before you use app.router.
...
app.use (function (req, res, next) {
console.log ("inside middleware");
next();
});
...
app.use(app.router);
Updated answer for Express 4 users from the Express 4 docs. See example from docs below. Note that app.router is deprecated and no longer used. I also added a dummy route to make the ordering clear.
You define error-handling middleware last, after other app.use() and routes calls
Example:
var bodyParser = require('body-parser');
app.use(bodyParser());
app.get('/', function(req, res) {
res.send('hello world');
})
app.use(function(err, req, res, next) {
// logic
});

Resources