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
});
Related
Pug file:
...
- var paths = flatSitemap(sitemap);
app.js file:
var fsm = require('./routes/fsm.js');
app.set('port', process.env.PORT || 4109);
app.set('views', path.join(__dirname, 'src/pug'));
console.log(path.join(__dirname, 'src/pug'));
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res, next) {
res.locals.flatSitemap = fsm.flatSitemap;
next();
});
app.locals.flatSitemap = fsm.flatSitemap;
app.get('/', function(req, res) {
res.render('./index', {flatSitemap: fsm.flatSitemap}); // works!!!
res.render('./index'); // Not working
});
So when I use the res.render using the options it works, but if I don't include the options and rely on pug reading res.locals it doesn't, and comes back with "flatSitemap is not a function".
The res object is not automatically passed to the view. Hence the message that flatSitemap does not exist or is not a function. You won't get around appending it as a parameter. You can make a condition with a binary logic OR operator.
app.get('/', function(req, res) {
res.render('./index', { flatSitemap: res.locals.flatSitemap || fsm.flatSitemap });
});
I installed cors module and coded like below.
var express = require('express'),
favicon = require('serve-favicon'),
cors = require('cors');
var app = express();
if (app.get('env') === 'development') {
app.locals.pretty = true;
}
app.set('view engine', 'pug');
app.set('views', './views');
app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/img/logo.ico'));
app.use(cors());
app.get('/', (req, res) => {
res.render('view');
});
app.listen(80, () => {
console.log('Server started on port 80');
});
After this I turned on server and tried to access files on server by this code.
$.getJSON('https://server.domain/global.json', data => {
console.log(data);
});
But It makes error.
I can access to js files but not json file.
What's the problem?
[+Edit]
I can get js files by
$.getScript('~/js/file.js');
But not by
$.get('~/js/file.js');
do you get the error after trying this:
app.get('/', cors(), (req, res) => {
res.render('view');
});
and
$.getJSON('https://server.domain/global.json', cors(), data => {
console.log(data);
});
Server in express don't allow you to access files directly.
if you want it to enable access files directly . you have to do it like this
app.use(express.static('public'))
now you can access files in public folder directly like
if there is file data.json in public, you can access it by localhost:3000/data.json.
Hope this is answer of your question
put the cors module as the first module that you load (use)
I finally solved this problem with code below.
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
next();
});
I'd like to set up some subdomains for my Node.js app. I've built my site with express.js, and now I'd just like to throw up a little web tool on a subdomain of my site. I've tried using the vhost middleware with little luck, but am open to other approaches.
Any help would rock!
Ideally, I could just drop a new express app in a sub directory change a few lines of code, maybe change some DNS settings at it would work. The reason I'd like this is so that I can reuse a fresh instance of stylus and jade with new layouts and css styles and so forth.
Here's my normal app.js, the commented line is the attempt to use vhost.
var express = require('express'),
routes = require('./routes');
var app = module.exports = express.createServer();
// Configuration
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', { layout: false });
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use('/courses', function (req, res, next) {
var privates = require('./.private.json'),
couch = require('nano')('https://' + privates.dbCreds.username + ':' + privates.dbCreds.password + '#wamoyo.iriscouch.com/');
});
app.use(require('stylus').middleware({
src: __dirname + '/public'
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
// VHOST - SUBDOMAIN
// app.use(express.vhost('adventures.innovationbound.com', require('./adventures/index').app));
app.use(function (req, res, next) {
res.status(404);
res.render('four', {
title: "Innovation Bound",
now: new Date().getFullYear()
});
});
app.use(function (err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
});
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/services', routes.services);
app.get('/events', routes.events);
app.get('/blog', routes.blog);
app.post('/contact', routes.contact);
// Courses
// app.get('/heartbeat', routes.heartbeat);
app.get('/courses', routes.courses);
// Tools
app.get('/point', routes.point);
app.listen(3000, function() {
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
This is using express 2.5, I wouldn't mind migrating over to 3 if need be.
I'm having some problems trying to implement some middleware in my app.
Specicially, the app.use() does not seem to catch and I don't understand why.
Below is roughly what I have.
routes/index.js
var Sessions = require('../events');
module.exports = exports = function(app) {
app.use(Sessions.isLoggedIn);
//app.use() does not catch but this does
//app.all('*', Sessions.isLoggedIn);
// Home Page
app.get('/', displayHome);
app.get('/:library/:books', displayLibrary);
}
events.js
module.exports = exports = {
isLoggedIn: function(req, res, next) {
console.log('isLoggedIn');
return next();
}
Any suggestions as to why app.use() is not catching?
UPDATE:
Here is the configuration in ape.js
app.configure(function() {
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.compress()); // compress responses
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(expressValidator);
app.use(express.cookieParser('locket'));
app.use(express.cookieSession({
key: 'locket',
secret: 'mySecret',
cookie: {httpOnly: true, expires: 0, path: '/'}
}));
// cache every file going out
app.use(function(req, res, next) {
if (!res.getHeader('Cache-Control')) {
res.setHeader('Cache-Control', 'public, max-age=' + (86400 / 1000));
}
next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
});
routes(app);
The router is responding to the request before your middleware function has a chance to run.
app.js sets up several other middleware functions, then uses app.router. You then call your routes/index.js file, which uses a new middleware function which gets added after app.router.
use your isLoggedIn function before the router, or use it specifically with the routes that need to check login state:
app.get('/', Sessions.isLoggedIn, function(req, res) { ... });
Useless middleware for testing purposes:
module.exports = function () {
return function rankick(req, res, next) {
if (Math.random() < 0.5) {
return next('Random kick...');
}
next();
};
};
Injected into a simple express app:
var express = require('express'),
http = require('http'),
path = require('path')
rankick= require('./rankick'),
util = require('util');
var app = express();
app.set('port', process.env.PORT || 8080);
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(express.static(path.join(__dirname, 'public')));
app.use(rankick()); // Using the middleware
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(function (req, res, next) {
res.end('Hello World!');
});
http.createServer(app).listen(app.get('port'));
When next() is invoked with the error string, console logs undefined followed by the 500 error:
undefined
GET / 500 28ms
GET / 200 4ms
undefined
GET / 500 5ms
Is it's this line in the errorHandler middleware. Maybe it expects to get a new Error('Random kick..')?
It's been a while since I used to default errorHandler so I am not 100% sure. In case it's not downvote and I'll remove this answer.
You should do
module.exports = function rankick(req, res, next) {
if (Math.random() < 0.5) {
console.log('Random kick...');
}
else
next();
};
Don't use return to pass the function. module.exports is the object that is passed when require is called.
Also next() is supposed to be called if you want to continue processing to next middleware. If you want to stop processing/kick request don't call next()