express methods having strange behaviors

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error express methods having strange behaviors on this date .

i have routes with the get method.

app.get("/info/teachers", controller1);

app.get("/info/teachers/:teacherid", controller2);
app.get("/info/students", controller3);
app.get("/info/students/:studentid", controller4);
app.get("/info/courses", controller5);
app.get("/info/courses/:courseid", controller6);

app.get("/info/courses/enrolled/:studentid", controller7);
app.get("/info/assists/teachers", controller8);
app.get("/info/assists/teachers/:teacherid", controller9);
app.get("/info/courses/:teacherid", controller10);

app.get("/info/assists/students", controller11);
app.get("/info/assists/students/:studentid", controller12);

all of them works except for app.get(“/info/courses/:teacherid”, controller10);

but if i move his position to:

app.get("/info/teachers", controller1);
app.get("/info/courses/:teacherid", controller10);

app.get("/info/teachers/:teacherid", controller2);
app.get("/info/students", controller3);
app.get("/info/students/:studentid", controller4);
app.get("/info/courses", controller5);
app.get("/info/courses/:courseid", controller6);

app.get("/info/courses/enrolled/:studentid", controller7);
app.get("/info/assists/teachers", controller8);
app.get("/info/assists/teachers/:teacherid", controller9);
app.get("/info/assists/students", controller11);
app.get("/info/assists/students/:studentid", controller12);

it just works; why is this happening? all the controllers works independtly and dont need information from the others.

Answer

There’s no distinction between /info/courses/:teacherid and /info/courses/:courseid. The router will pick the first that matches, and they both match the same urls.

In your second snippet, controller6 will never be called.

You’ll either need to change that route to something like /info/courses/taught/:teacherid (like you did with /enrolled), or you’ll need to have a single route /info/courses/:someId with a controller that can distinguish whether someId is a teacher id or a course id. (Different prefixes, maybe?)