Working with express.js for the first time, and I am stuck on adding my first route.
My route is defined in app.js like so:
app.get('/user/:id/photos', function(req,res){
res.send('user' + req.params.id);
});
However curling to http://localhost:3000/user/1/photos just results in a “cannot GET” error.
The index file that was included with express seems to work just fine though.
This is my express app.js file:
var express = require('express'),
routes = require('./routes');
var app = module.exports = express.createServer();
// Configuration
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());
});
// Routes
app.get('/', routes.index);
app.get('/test', routes.test);
app.get('/user/:id/photos', function(req, res) {
res.send('user' + req.params.id);
});
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Try changing the routes from most specific to least specific. Routes are matched in order. If it matches on the
'/'route first, it will pass toroutes.index, and never get a chance to router to the/user/:id/photosfunction.So, instead of:
Try:
As a side note, I think
/user/photos/:idseems better but I tried out/something/:id/somethingelsein my app, and it worked fine.