Home > Enterprise >  why are my express sub routes not working
why are my express sub routes not working

Time:12-29

why are these two endpoints not working with routes.use http://127.0.0.1:3000/api/students http://127.0.0.1:3000/api/teachers while my http://127.0.0.1:3000/api and http://127.0.0.1:3000/api/api are working just fine. I am using express.js server and router() with typscript.

this my server.ts file

import express from 'express';
import routes from './routes/index'

// create an application object
const app = express();
// defint a port
const port = 3000;

//apply router middleware to application
app.use('/api', routes);


// define a route handler for hompage
app.get('/', (req, res) => {
    res.send('Hello, world!\n welcome to the server.');
});


//start the express server
app.listen(port, ()=> {
    console.log(`server started at localhost:${port}`)
});

this my index.ts inside ./src/routes directory

import express from 'express';
import students from './api/students';
import teachers from './api/teachers';

const routes = express.Router();

// define a route handler for hompage
routes.get('/', (req, res) => {
    res.send('connected to the server. main api route');
});
// define routes fro other paths
// routes.get('/api', (req, res) => {
//     res.send('connected to the server. secondary api route');
// });
routes.use('/api', routes);
routes.use('/students', students);
routes.use('/teachers', teachers);

export default routes;

and this students.ts in ./src/routes/api

import express from 'express';
const students = express.Router();


// define a route handler for api/students
students.get('/students', (req, res) => {
    res.send('connected to the server. students route');
});

export default students;

CodePudding user response:

Here, the actual endpoint for the API for the students.ts is: /api/students/students because in the student.js file the path starts from the /students so the final URL will be
http://127.0.0.1:3000/api/students/students

Moreover, if the endpoint in the students.ts file is changed from /students to / then it will work with the http://127.0.0.1:3000/api/students URL

  • Related