简体   繁体   中英

Express routes returning 404s

I have a couple of simple routes that I have misconfigured and not sure why.

app.js:

//app setup
var http = require('http');
var bodyParser = require('body-parser');
var express = require('express');
var routes = require('./routes');
var agent = require('./routes/agent');
var config = require('./config');
var app = express();


app.server = http.createServer(app);

app.use(bodyParser.json({
    limit : config.bodyLimit
}));

app.use(bodyParser.urlencoded({
    extended : true
}));

app.use('/v1', routes);
app.use('/v1/agent', agent);

app.server.listen(config.port);

console.log('API listening on port ' + app.server.address().port);

module.exports = app;

This returns responses on the /v1/ route (index.js):

'use strict';

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

router.get('/', function (req, res) {
    res.status(403).json({
        message: 'Invalid request.'
    });
});

module.exports = router;

in the agent route, I have a POST handler that is being handled correctly at /v1/agent/login . But while a GET routed at /v1/agent/ works, a GET routed to /v1/agent/123 returns a 404:

'use strict';
var agentController = require('../controller/agent.js');
var express = require('express');
var router = express.Router();

function handleError(objError, res) {
    res.status(500).json({ errorMessage : objError.message });
}

router.get('/', function (req, res) {
    res.status(200).json({
        message: 'OK' // works fine
    });
});

router.get('/:id'), function (req, res) {
    var agentNum = req.params.id;
    res.send(req.params); // 404 here

    try {
        //res.status(200).json({ message: 'hello agent.'});
    } catch (err) {
       // handleError(err, res);
    }
};


router.post('/login', function (req, res) {
    var agentNum, password;
    // works fine 
});

router.post('/pwr', function (req, res) {
    //also works fine
});
module.exports = router;

My understanding is that the app.use method should redirect the route and any GET requests appended to that route to the one I specified (agent), so why is it that the one with params fails while the root one succeeds?

Thank you

You're not passing the callback correctly.

router.get('/:id' )

router.get('/:id', function(req, res) {
    var agentNum = req.params.id;
    res.send(req.params); // 404 here

    try {
        //res.status(200).json({ message: 'hello agent.'});
    } catch (err) {
       // handleError(err, res);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM