Create a gist now

Instantly share code, notes, and snippets.

// vendor
var express = require('express');
var app = express();
// depending on the placement, we can either catch or override routes
app.use(app.router);
// every route in the routes/user.js file will be served under /user
app.use('/user', require('./routes/user').middleware);
// every route in the routes/post.js file will be served under /post
app.use('/post', require('./routes/post').middleware);
// last middleware will be 404 handler
app.use(function(req, res, next) {
// 404 handler
});
/// regular routes
app.get('/', function(req, res, next) {
res.send('Hello World!\n');
});
/// go go go!
var server = app.listen(3000);
{
"name": "routes-example",
"version": "0.0.0",
"dependencies": {
"express": "3.0.6"
}
}
// vendor
var express = require('express');
var router = new express.Router();
// routes also have the .param method to allow for easier resource loading
// in this case we will make sure all our routes load the post
router.param('post_id', function(req, res, next, post_id) {
// simulate loading a post
setTimeout(function() {
req.post = { name: 'foo' };
next();
}, 1000);
});
router.get('/:post_id', function(req, res, next) {
res.send(req.post.name + '\n');
});
router.post('/:post_id/comment', function(req, res, next) {
// we could add the comment to req.post here
res.send('\\o/\n');
});
module.exports = router;
// vendor
var express = require('express');
var router = new express.Router();
router.get('/foo', function(req, res, next) {
// for the full url
res.send(req.originalUrl + '\n');
// for just /foo
//req.url
});
router.post('/bar', function(req, res, next) {
res.send(req.originalUrl + '\n');
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment