Change Express view folder based on where is the file that res.render() is called

You can use the method set() to redefine express’s default settings. app.set(‘views’, path.join(__dirname, ‘/yourViewDirectory’)); Express documentation For a dynamic path change you can do something like this: var express = require(‘express’); var path = require(‘path’); var app = express(); app.engine(‘jade’, require(‘jade’).__express); app.set(‘view engine’,’jade’); app.customRender = function (root,name,fn) { var engines = app.engines; var cache = … Read more

npm start vs node app.js

The two of these commands aren’t necessarily the same. npm start runs whatever the ‘start’ script config says to run as defined in your ‘package.json’, node app.js executes the ‘app.js’ file in ‘node’. See http://browsenpm.org/package.json for more info. So if you had the following package.json then the commands are completely different. { “name”: “my cool … Read more

Express js form data

You should install body-parser through npm-install. Now it comes as a separate middleware. After that add following line in your app.js var bodyParser = require(‘body-parser’); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); // in latest body-parser use like below. app.use(bodyParser.urlencoded({ extended: true })); It parses the post request as an object. You will get your variables in req.body. In your … Read more

Chaining multiple pieces of middleware for specific route in ExpressJS

Consider following example: const middleware = { requireAuthentication: function(req, res, next) { console.log(‘private route list!’); next(); }, logger: function(req, res, next) { console.log(‘Original request hit : ‘+req.originalUrl); next(); } } Now you can add multiple middleware using the following code: app.get(“https://stackoverflow.com/”, [middleware.requireAuthentication, middleware.logger], function(req, res) { res.send(‘Hello!’); }); So, from the above piece of code, … Read more

Error: Cannot find module ‘ejs’

I had this exact same problem a couple of days ago and couldn’t figure it out. Haven’t managed to fix the problem properly but this works as a temporary fix: Go up one level (above app.js) and do npm install ejs. It will create a new node_modules folder and Express should find the module then.

Express.js – How to check if headers have already been sent?

Node supports the res.headersSent these days, so you could/should use that. It is a read-only boolean indicating whether the headers have already been sent. if(res.headersSent) { … } See http://nodejs.org/api/http.html#http_response_headerssent Note: this is the preferred way of doing it, compared to the older Connect ‘headerSent’ property that Niko mentions.