I have a Node/Express backend with TypeScript.
If I run the root route in Postman localhost:8000/
after changing and saving a file I get a proper response. However, if I run localhost:8000/user
after changing and saving a file I get an automatic 404 HTML response.
Only if I first run the root route and only then run the child route, does it work.
What am I doing wrong here?
index.ts
// External
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
// Internal
import { uri } from '../backend/config/dbConsts';
import masterRoute from './api/masterRoute';
module.exports.mongoose = mongoose;
const app = express();
const PORT = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
// Defines the routes used.
app.use('/', masterRoute);
app.listen(PORT, () => {
console.log(`??[server]: Server is running at https://localhost:${PORT}`);
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
});
export default app;
masterRoute.ts
import express, { Router } from 'express';
import userRoute from './routes/user.route';
const router: Router = express.Router();
router.get('/', async (req, res, next) => {
router.use('/user', userRoute);
// Returning 400 here since all requests must enter into an actual routing file.
res.status(400).send('Bad route. masterRouter.');
});
export default router;
userRoute.ts
import express, { Router } from 'express';
const router: Router = express.Router();
import userController from '../../controllers/user.controller';
router.get('/', async (req, res, next) => {
try {
const users = await userController.getAllUsers();
res.status(200).send(users);
} catch (err) {
next(err);
}
});
});
export default router;
question from:
https://stackoverflow.com/questions/65951363/weird-behavior-using-parent-child-routing-file 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…