express without a template - node.js

Is there a reason why I should avoid doing this?
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/views'));
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
var html_dir = './views/';
app.get('/', function(req, res){
res.sendfile(html_dir + "login.html");
});

you need to use res.write and res.end() and just read the content's of the file vis the core require('fs') you can use res.set(field, [value]) for the headers
full docs

Related

less-middleware does't work - "Express 500 Error: Unrecognised input"

I'm using Express framework with less-middleware and jade template engine
When I'm trying to get my css file in browser "/css/style.css" - I get the error
"Express 500 Error: Unrecognised input"
Here is basic setup in app.js
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {
layout: false
});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get("/api/places", api.getAllPlaces);
app.get("/api/place/:id", api.getOnePlace);
app.all('*', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Any help appreciated! Thanks.
That was just typo in *.less file. Thanks!

Global variable express node.js

I am trying to get variables that I can get everywhere in my code
I found a solution but that's not very clean
//environment.js
module.exports.appName = "appName";
and my app.js
var express = require('express')
, routes = require('./routes/main')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
environment = require('./environment');
app.configure(function(){
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(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.home);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
In this way my var works, I can access environment.appName everywhere, but Y would have better solution
Thanks
There is a global scope in node.js.
In the main file (the one you put behind node in command line,) all variables defined are in global scope.
var x = 100;
// which global.x === 100
And in other files loaded as module, the scope is not global but a local sandbox object, so you need global.x to access the same x in main file.
Seems it looks better than use a require().

ExpressJS 3.0 How to pass res.locals to a jade view?

I want to display a flash message after a user fails to sign in but I just can't get the variables to show up in my Jade views.
I have some pieces, I know I have to use this in my app.configure():
app.use (req, res, next) ->
res.locals.session = req.session
And I'll set what the flash message is after the user POSTS the wrong password:
exports.postSession = (req, res) ->
users = require '../DB/users'
users.authenticate(req.body.login, req.body.password, (user) ->
if(user)
req.session.user = user
res.redirect(req.body.redirect || '/')
else
req.session.flash = 'Authentication Failure!'
res.render('sessions/new', {title:'New', redirect: req.body.redirect })
)
I don't know how to access res.locals.session in my Jade file. I doubt I am setting everything up right. This question is a lot like this one: Migrating Express.js 2 to 3, specifically app.dynamicHelpers() to app.locals.use? but I still can't get it to work. It would be much appreciated if someone could show me just a simple example of setting values in res.local and accessing them in a view.
p.s. I do know about connect-flash but I need to understand how to make things available in views.
This is my app:
app.configure(() ->
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.bodyParser())
app.engine('.jade', require('jade').__express)
app.use(express.methodOverride())
app.use(express.cookieParser())
app.use(express.session({ store: new express.session.MemoryStore({reapInterval: 50000 * 10}), secret: 'chubby bunny' }))
app.use(express.static(__dirname + '/public'))
app.use((req, res, next) ->
res.locals.session = req.session
next()
)
app.use(app.router)
)
Just to give a short summary for everyone who has the same problem and got the impression that is was solved changing res.redirect.
It is very important to put your app.use middleware before app.router. See the comments by TJ Holowaychuck, the author of express
https://groups.google.com/d/msg/express-js/72WPl2UKA2Q/dEndrRj6uhgJ
Here is an example using a fresh installation of express v3.0.0rc4
app.js:
app.use(function(req, res, next){
res.locals.variable = "some content";
next();
})
app.configure(function(){
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(express.static(path.join(__dirname, 'public')));
});
index.jade:
extends layout
block content
h1= title
p Welcome to #{title}
p= variable
If you are using express.session() you must call your function AFTER express.session() but BEFORE app.router, inside of app.configure().
app.js
app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session());
// Give Views/Layouts direct access to session data.
app.use(function(req, res, next){
res.locals.session = req.session;
next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
index.jade
extends layout
block content
h1= title
p My req.session.var_name is set to #{session.var_name}

express.compress() and express.responseTime() not working for controller's output

I've the following scaffolded express application:
var
express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, _ = require('underscore');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 5000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.compress());
app.use(express.responseTime());
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
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'));
});
The only modification I've made to code generated by express generator:
app.use(express.compress());
app.use(express.responseTime());
The problem: processed to LESS files are gzipped and has X- HTTP-header with response time, but output from my controllers (HTML pages) is not gzippped and is served without headers.
Maybe I understand connect middleware wrong?
For the pages generated by your routes to be compressed (I assume that's what you mean by controllers) you need to move this line:
app.use(app.router);
after this line:
app.use(express.compress());
express.compress only affects those components added after it.
For express 4, it is necessary to install the module.
var compress = require('compression')();
app.use(compress);

How to configure express.js/jade to process html files?

I would like to configure jade engine to handle .html files in my views folder. Here is my currentserver configuration:
app.configure(function(){
var pub_dir = __dirname + '/public';
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: nconf.get("site:secret") }));
app.use(everyauth.middleware());
app.use(require('less-middleware')({ src: pub_dir, force:true }));
app.use(express.static(pub_dir));
app.use(app.router);
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);
});
https://github.com/visionmedia/express/blob/master/examples/ejs/index.js
app.engine('.html', require('jade').__express);
Make sure you already have jade in your node_modules
npm install --save jade
In express 4.x, you can simply set the view engine to jade.
app.set('view engine', 'jade')

Resources