Last active
November 25, 2015 14:40
-
-
Save Chris927/5e19011ec4d46fb66d2e to your computer and use it in GitHub Desktop.
NodeJS Express, use middleware to protect routes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
var port = 3100; | |
app.listen(port, function() { | |
console.log('listening on port ' + port); | |
}); | |
/* public routes */ | |
app.get('/', function(req, res, end) { | |
res.status(200).send('Hello, world'); | |
}) | |
app.get('/login', function(req, res, end) { | |
res.status(200).send('login here'); | |
}) | |
app.use(function(req, res, next) { | |
console.log('req.url', req.url); | |
if (req.session && req.session.user) { | |
return next(); | |
} | |
res.redirect('/login'); | |
}); | |
/* routes protected by login */ | |
app.get('/profile', function(req, res, end) { | |
res.status(200).send('my protected profile'); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment