Jimonio
Jimonio

Reputation: 1

When I params in url, ExpressJS is not calling any method, and is giving me a CANNOT GET error

I have been all day trying to figure out this one. I am using Node.js, Mongoose and Express.js "version 9.7.1",

A snippet from my app.js:

app.use('/students', studentsRouter);
app.use('/teachers', teachersRouter);

My router:

export const studentsRouter = router();
const repo = StudentMongoRepo.getInstance();
const controller = new StudentController(repo);

studentsRouter.get('/', controller.getAll.bind(controller));
studentsRouter.get('/:id', controller.getById.bind(controller));

studentsRouter.post('/login', controller.login.bind(controller));

studentsRouter.post(
  '/register',
  controller.register.bind(controller)
);

The method called by the specific route I want:

async getById(req: Request, resp: Response, next: NextFunction) {
    try {
      debug('getById');
      if (!req.params.id)
        throw new HTTPError(404, 'Not found', 'ID not founf in params');

      const id = req.params.id;
      debug('req.params: ', req.params);

      const data = await this.repo.queryId(id);
      if (!data) {
        throw new HTTPError(
          401,
          'Student does not exist',
          'Student does not exist'
        );
      }

      resp.status(201);
      resp.json(data);
    } catch (error) {
      next(error);
    }
  }

The thing is, all the routes work fine, I have a DEBUG at the beggining of each method, which gets called for every route except for this one: studentsRouter.get('/:id', controller.getById.bind(controller));

I tried with Postman with this url: http://localhost:4500/students/123 (and many more), and I always get Cannot GET /students/0

In my terminal: GET /students/0 404 0.618 ms - 149

I honestly don't know what is happening since I did a similar project before and the route is exactly the same. :(

I have tried writting this test in my router:

studentsRouter.get('/test/:id', (req, res) => {
  console.log('Test route is being called.');
  res.send('Test route');
});

It also came back as CANNOT GET 404.

But the routes '/login' and '/register' work perfectly, they are with POST though. Could it be a problem with the GET? '/' works fine, when I send the request http://localhost:4500/students all the students show.

I have also tried changing the order of the routes, but still it is not working.

Upvotes: 0

Views: 33

Answers (0)

Related Questions