Waltari Waltari - 1 year ago 74
Javascript Question

Route an entire folder and its content

I want to protect a folder and its content by redirecting the user back to index.

I've tried this, but it only works partially.

var express = require('express');
var path = require('path');
var http = require('http');
var app = express();

app.set('port', 8080);
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));

app.get('/', function(req, res) {

app.get('/protected/*', function(req, res, next) {

//activating server
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));

This routes, for example, "localhost:8080/protected" and "localhost:8080/protected/asdf", but not "localhost:8080/protected/otherPage.html".

In this case asdf is not an actual file, but otherPage.html is. So if the file is there it doesn't redirect, but if it is not then it redirects. Why is this?

Answer Source

Your line dealing with static files app.use(express.static(path.join(__dirname, 'views'))); appears before app.get('/protected') so its being matched first.

If you moved the static handler to later in the code this would work as you require.

However, I would recommend splitting the static items into a separate folder to guard against accidentally revealing any server-side code you might be including in ejs files in the views folder.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download