Routing with express.js - Cannot GET Error

2019-02-18 08:07发布

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);

2条回答
\"骚年 ilove
2楼-- · 2019-02-18 08:41

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-18 08:44

Your example looks fine. It works for me (express 2.5.8, node 0.6.11). Actually, while bryanmac is correct that order matters, a request for /user/1/photos won't match the route / - it would for other routes, e.g. /*, but not / (or /test for that matter).

What version of express, node do you run? Also, can you post your routes.js too?

查看更多
登录 后发表回答