I have read around about this a lot and it seems like its an issue that confuses a lot people. I am doing a project with express and I dont want to you any tempting engines, I am using backbone with underscore and thats enough for me. I want to write plain HTML and render them..
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/views'));
app.set('views', __dirname + '/views');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use( express.cookieParser() );
app.use(express.session({ secret: 'topsecret' } ));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
this is what I have so far.. I am having a hard time to understand how express knows to render the index.html file as my home page even though I have this:
app.get('/', function(req, res){
console.log("Heyyyyyy");
});
I would expect nothing to be rendered and "Heyyyy" to be printed but express renders the index.html and doesnt print "Heyyyy"
Express evaluates middleware in the order in which they are configured.
You have a static file handler before your app.router.
Take the index.html file out of the __dirname + '/views' directory.
You also have a static file handler at the bottom of your middleware stack. Static file handlers should be at the top of your middleware stack. When they're at the bottom of your middleware stack each request unnecessarily processes all of the stack. For example, you don't need to run express.bodyParser() when serving static files.
Related
When using Express version 4.15.2, the following (apparently commonly encountered) error appeared in the browser--- 500 Error: Failed to lookup view "index" at Function.app.render. I've read the solutions offered to several such victims, but my __dirname value is indeed pointing to the correct views folder, and the correct path for 'views' is indeed constructed in the app.js file which I'm using in the Windows command line (i.e., >node app.js). The only thing I notice that seems strange is that the 'index' file present in the views folder is named 'index.jade'. I'm using pug instead of jade. In fact, hasn't use of Jade been discontinued? Could this be the problem? Should there be a '.pug' extension now for windows, or no extension at all on the index file?
Per your request to see the configuration (although, it's pretty standard, and I didn't change anything but the 'jade', to 'pug'), the following is the only configuration I see in app.js. (And changing the view engine from 'jade' to 'pug' got rid of the error of not finding 'jade'.)
// 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(express.static(path.join(__dirname, 'public')));
// development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
Yes, indeed, all I had to do was to change the extension .jade to the extension .pug on both the index and the layout file, and that solved the problem. Thus, the problem wasn't __dirname; that was indeed correct. The problem was that it didn't like the .jade extension.
Thanks for the ideas anwyay.
I have this piece of code here:
var express = require('express')
, http = require('http')
var app = express();
var server = app.listen(1344);
var io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));
app.get('/', function(req, res){
if(req.session){
console.log(req.session);
}
console.log('ok');
});
The code inside the app.get() callback is not being called. If I comment out the app.use(express.static(__dirname + '/public')) line, then the callaback works. I've tried changing the order, but its like a lottery! I would prefer to know whats going wrong here.
I'm sure this have to do with lack of knowledge from my part on how the middleware is called. Can someone help me understand this problem?
Basically I just want to perform some logic before the files are served and the index.html is load on the browser. By the way placing the app.get() before the app.use(express.static()) line, does not did the trick!
Your static file middleware should go first.
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));
And you should be adding a use for app.router as well.
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'secret'}));
app.use(app.router);
Middleware is processed in order for each request. So if you have an index.html in your static files then requests for yourdomain.com/ will never make it to the app.router because they will get served by the static file handler. Delete index.html and then that request will flow through to your app.router.
Rename your index.html file to something else. It is that simple
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
if(req.session){
console.log(req.session);
}
console.log('ok');
res.sendfile(new_index_file);
});
I believe, you have 3 options here:
1) Mount your app.get('/') route (possibly, using app.router) before static middleware, so that they take precedence. Middleware that is mounted first, processes a matching request first.
2) Use a path prefix for your static paths like app.use('/static', express.static('public'));, so that statics is served from example.com/static/...
3) Want to act smart and shoot yourself in the leg? :) Sometimes people use Accept headers and content negotiation to serve 2 different content types from the same url in different circumstances. You can make your static middleware check for a specific content type in Accept header and process request, only if requests's Accept header wants a proper type. Otherwise, it will pass the processing down the stream to you / view. You can customise your static middleware content negotiation in req.accepts.
Im using ejs as template engine with default layout off, but i activate it on demand via {layout:True}, i have two urls '/' and '/session/new' the css and js are show OK in the former but in the second one they would adress to 'http://localhost/sessions/public/stylesheets/my.css'
i tried using *stylesheet_link_tag* as seen here (http://railwayjs.com/), but i guess its only for railwayjs, is there anything im missing,
im thinking of a workaround of addind a depth variable to precede the link and that would be filled with '/..' depending on the route
here is my configure
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {layout: false});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
I hope you are well.
I'm suddenly unable to render any external javascript in jade templates! To get to the bottom of things, I stripped it down to the bare minimum :
Node 0.6.11, Express 2.5.8, jade 0.20.3
app.js
var express = require('express')
, routes = require('./routes');
var app = module.exports = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
app.get('/', function(req, res){
res.render('index', { title: 'Express' });
});
app.listen(3000);
layout.jade
!!!
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(type='text/javascript', src='/javascripts/script.js')
body!= body
script.js
alert('hello!');
It seems to me that when I run the server and load http://localhost:3000/, I should straightaway get a 'hello!' message, but it just runs straight to the normal page.
What's more, if I manually type
script
alert('hello!')
into the layout.jade template I get the message just as I should. It is just not loading the static script. And I have certainly checked that 'script.js' is in '/public/javascripts/' just as it should be.
Any advice would be very welcome!!!
Thanks in advance
you need to pass your script from the controller like that:
app.get('/', function(req, res){
res.render('index', { title: 'Express', scripts: ['javascripts/script.js']});
});
and then in your head in layout.jade:
- each s in scripts
script(src=s)
Make sure your js files are exposed as static resources.
In layout.jade...
!!!5
html
head
script(src='js/helper.js')
In app.js...
app.use(express.static(__dirname + '/public'));
Once I put the 'js' folder under the 'public' folder, helper.js loaded without issue. Simple, but I'm new to this whole thing and I didn't get that at first.
Why do you have a beginning forward slash '/' in your Jade script tag? With your script in <root_dir>/public/javascripts/script.js, the correct way to reference it in Jade is script(src="javascripts/script.js"). At least that is what is working on my installation. The same is true for other assets like CSS or images in the /public directory.
Thanks to Rob (you can find his answer above), for pointing in right direction. I just want to add a little reference so it might seem more natural than any magic.
In the express documentation here, its mentioned that if static files like css, images etc are to be served then one need to declare it using
app.use(express.static("_dirName"));
I was facing same issue with using images in html code. With this, it works fine now.
So the problem is that node.js doesn't send my javascript files correctly. I can find them in the html code, but they are not executed by the browser. Those js files don't even appear in the firebug's NET panel when I reload the page.
I am using Express with Jade.
Any ideas how to fix this issue? Or what's causing it?
Make sure you have express.static set properly in app.configure.
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
// Also, make sure you have the most updated versions of express and node.js. Both change often.