user677526
user677526

Reputation:

Express 4 router.route: route not found

I'm running into a strange issue. The first route is working, but the parameterized route returns a 404 error.

var express = require('express');
var router = express.Router();

router.route('/')
    .get(function (req, res, next) {
        res.send('A list of vehicles.');
    })
    .post(function (req, res, next) {
        res.send('You added a vehicle!');
    });

router.route('/:id')
    .get(function (req, res, next, id) {
        res.send('Vehicle: ' + id);
    })
    .put(function (req, res, next, id) {
        res.send('You edited vehicle: ' + id);
    });

If I add this route:

router.route('/test')
    .get(function (req, res, next) {
        res.send('This is a test.');
    });

...I can hit that endpoint. This also seems to work with another router I'm using, which is using router.get(path, function) and router.post(path, function) instead of the router.route(path).get()... methodology.

Am I missing something obvious here? I'm using Express ~4.12.

Upvotes: 0

Views: 343

Answers (1)

user677526
user677526

Reputation:

Gah, I'm an idiot. Just figured this out. I saw an example that used this function signature:

.get(function (req, res, next, id) {
        res.send('Vehicle: ' + id);
    })

This apparently doesn't work. I'm not sure if the http methods check the arity of the function, but this did work:

.get(function (req, res, next) {
        res.send('Vehicle: ' + req.params.id);
    })

I don't remember where I saw that example, but hopefully this helps someone.

Upvotes: 1

Related Questions