Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Routing with express.js - Cannot GET Error

Routing with express.js - Cannot GET Error

Problem

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);
Problem courtesy of: Msencenb

Solution

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 to routes.index, and never get a chance to router to the /user/:id/photos function.

So, instead of:

app.get('/', routes.index);
....
app.get('/user/:id/photos', function(req,res){

Try:

app.get('/user/:id/photos', function(req,res){
....
app.get('/', routes.index);

As a side note, I think /user/photos/:id seems better but I tried out /something/:id/somethingelse in my app, and it worked fine.

Solution courtesy of: bryanmac

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Routing with express.js - Cannot GET Error

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×