Express catch all route excluding static content such as css and js - node.js

New to Node.js.
I'm using the VS2015 Express 3 template. How can I write my routing to:
Have a page at "/"
Have a a catch all route that responds with the home page "/"
Doesn't interfere with JS and CSS files
I.e., I tried the following, but then the JS and CSS files in the public directory respond with 404 don't render or execute. I thought that the static files code would handle it, but it does not. It works until I add the block with "*".
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
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('*', function (req, res) {
res.send('/', 404);
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});

The solution, as suggested by jfriend00, is to add the following line below app.get('/', routes.index):
app.use(routes.index);

Related

res.Send it results in 404 error?

Hi I am trying display the message : respond with a resource from routes folder/user.js
exports.list = function (req, res) {
res.send("respond with a resource");
};
But I am getting an error 404 in command prompt.And in url
localhost:8080\user where the response is sent I get the message:
Cannot GET /user
my app.js has code:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
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);
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
The example I am working on is from https://www.youtube.com/watch?v=czmulJ9NBP0. and time is at 1.37.41
Your route is named /users not /user. So try navigating to /users in your browser instead and it should work.

Send 404 header from not existent static content when using * route in Express

I'v got express app like this.
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
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(express.cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('*', function(res,req) {
req.render('index', {title: "Title"});
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Because of using app.get('*') request to not existent static files responses with rendered index.ejs file instead of error 404.
Is there any way to fix it without additional conditions in routes?
Just add something like:
app.get(/\/(js|css|img)\/.*/, function (req, res) {
res.send(404);
});
before app.get('*'). Any request to /js that wasn't already matched by the static middleware references an file that does not exist.
Resolved problem by nginx proxying

How to add my existing views,stylesheets,javascripts to express?

I have an existing coded frontend i.e views,javascripts,stylesheets (https://github.com/stdrunk/Taskr) and I intend to add this to the express framework so that i can link it to the db.
I added the contents to the public folder. The javascripts in the javascript folder, css in stylesheets, and images in images folder.
Then i changed the code of app.js according to this Render basic HTML view?
Now when run app.js and open the page in the browser i get a stripped version of my original page.
No error comes in the console.
This is my app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
//app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
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);
app.get('/home', function (req, res)
{
res.render('index.html');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
You could put all those dirs under a 'public' dir, and then use:
app.use(express.static(__dirname + '/public'));
That way, express will always just send anything requested from those directories, and you won't need to worry about static files at all.
Although, I do recommend keeping something like Apache running on your server to serve static files. Images especially.

How to configure kally-razor with express nodejs?

A razor view engine for nodejs.
https://github.com/nufyoot/kally-razor
I have tried something like this.. but no luck.
var razor = kallyrazor({
root: __dirname + '/views/',
layout: 'shared/layout.html'
});
app.engine('html', function (path, options, fn) {
fn(null, razor.render(path, options));
});
Worked for me. Did you include the view engine?
app.set('view engine', 'cshtml');
Note: I chose the use the cshtml extentionm just for vanity.. (And also in Sublime if that is your editor the razor syntax highlighter, https://github.com/joseph-turner/Razor)
Full code:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var KallyRazor = require('kally-razor');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'cshtml'); // NOTE THE VIEW ENGINE
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// Setup KallyRazor
var razor = KallyRazor({
root: __dirname + '/views/',
layout: '/shared/layout.cshtml'
});
app.engine('cshtml', function (path, options, fn) {
fn(null, razor.render(path, options));
});
// development only
if ('development' == app.get('env')) {
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'));
});

Nodejs cannot get /login

Hi i am following peepcode nodejs screencast, now i have an issues of rendering the login form. My code are as follow:
app.js
/**
* Module dependencies.
*/
require('coffee-script');
var express = require('express')
, http = require('http')
, path = require('path');
var app = express();
// 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());
}
require('./apps/authentication/routes');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and my i have a routes within authentication folder. The code as follow:
routes.coffee
routes = (app) ->
app.get '/login', (req,res) ->
res.render "views/login",
title: 'Login'
stylesheet: 'login'
module.exports = routes
The coffee script indentation all works fine, but i have an error when i navigate localhost:3000/login on browser. The error it display are Cannot GET /login. Where am i wrong?
In app.js, change this line:
require('./apps/authentication/routes');
to this:
require('./apps/authentication/routes')(app);
What is happening is that in routes.coffee, you're exporting a function that takes a single arg, 'app', and then sets up the route on your app object. You need to call it passing app as the argument.

Resources