getting 404 not found error when nesting routes in express js

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.

New contributor

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

New contributor

Kamil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật