Michael Kunzmann Michael Kunzmann - 1 month ago 12
Javascript Question

Express subrouter returns 404

I have this router (http/api/ping.js):

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

router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});

module.exports = router;


This router is embedded into this router (http/api/index.js):

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

router.get('/', function (req, res) {
res.send('You called /api');
});

router.use('/ping', require('./ping'));

module.exports = router;


And this router is used by my Express.js app (app.js):

var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./config').logger;

// Create app
var app = express();
var server = http.createServer(app)
var io = require('socket.io')(server);

// App config
app.use(bodyParser.json());
app.use('/api', require('./http/api'));

// Display requests on console
app.use(function (req, res, next) {
logger.trace(req.method, req._parsedUrl.href);
next()
});

module.exports = {
app: app,
server: server
};


When I run the app,
/api
returns
You called /api
, but
/api/ping
gives me a 404.

I am using Node 6.9.1 and Express ^4.14.0

Answer

I think order matters in this scenario. Try putting /ping above the / get route.

router.use('/ping', require('./ping'));
router.get('/', function (req, res) {
    res.send('You called /api');
});

Also in your ping route you say the path to your route is /ping you also say it is /ping when you import it to the other router, which would make the path /api/ping/ping

change

router.get('/ping', function (req, res) {
    res.send("You called /api/ping");
});

to

router.get('/', function (req, res) {
    res.send("You called /api/ping");
});
Comments