I’m working on rest api for my application and I have problem with nesting routes in express. I have nested routes and when I try to send request to nested url express sends back 404 not found.
index for all api routes (src/routes/index.ts):
import { Router } from 'express';
import accountRouter from './accounts.js';
import cashflowRouter from './cashflows.js';
const api = () => {
const router = Router();
// cashflows <- 404
router.use('/accounts/:account-id/cashflows', cashflowRouter());
// accounts <- this works well
router.use('/accounts', accountRouter());
return router;
}
export default api;
cashflow router (src/routes/cashflows.ts)
import { Router } from 'express';
import cashflows from '../controllers/cashflows.js';
const api = () => {
const router = Router();
// GET /accounts/:account-id/cashflows <- get all cashflows
router.get('/', cashflows.find);
// GET /accounts/:account-id/cashflows/:id <- get one cashflow
router.get('/:id', cashflows.findOne);
// POST /accounts/:account-id/cashflows <- add cashflow
router.post('/', cashflows.add);
// PATCH /accounts/:account-id/cashflows/:id <- get all cashflows
router.patch('/:id', cashflows.update);
// DELETE /accounts/:account-id/cashflows/:id <- get all cashflows
router.delete('/:id', cashflows.remove);
return router;
}
export default api;
I’ve been searching for a solution, but I can’t find one.
Strange thing is that when I send request to nested url with account-id
param empty I don’t get 404 error. My express version: ^4.19.2
I tried using cashflowRouter
as middleware for accountRouter
and set mergeParams
property of casflowRouter
to true
(It didn’t work). I also tried defining nested route directly in index.ts file (not what I want) and It worked.
Here’s code I tried:
router.get('/accounts/:id/example', (req, res) => {
res.json(req.params.id);
})
that route was above all other routes.
Kamil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Responding to request of Chuckwujiobi Canon:
index.ts file:
import http from 'node:http';
import express from 'express';
import { expressjwt, Params } from 'express-jwt';
import database from './config/database.js';
import getPublicKey from './utils/getPublicKey.js';
import apiRouter from './routes/index.js';
const {
PORT,
ISSUER_BASE_URL,
BASE_URL,
} = process.env;
const publicKey = getPublicKey();
const authConfig: Params = {
secret: publicKey,
algorithms: ["RS256"],
issuer: ISSUER_BASE_URL,
audience: BASE_URL,
}
const app = express();
const server = http.createServer(app);
// middleware
app.use(express.json());
app.use(express.urlencoded({
extended: true,
}));
app.get('/api/v1', (req, res) => {
res.json({
message: 'Welcome to expens rest api v1!',
});
});
app.use('/api/v1', expressjwt(authConfig), apiRouter());
server.listen(PORT, () => {
console.log(`Server up on localhost:${PORT}!`);
});
const gracefulShutdown = () => {
server.close(async () => {
await database.end();
console.log('closed connection to database!');
server.closeAllConnections();
console.log('closed all connections!');
process.exit(0);
});
}
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
process.on('SIGUSR2', gracefulShutdown);
one of requests that resulted in 404:
postman screenshot
rest-api-host
is localhost
Kamil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2