Routing with express.js - Cannot GET Error

混江龙づ霸主 提交于 2019-12-01 04:21:37

问题


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

回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/9474951/routing-with-express-js-cannot-get-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!