Cannot get route

Issue

I am trying to create my first express app, however I already have some issues. I am not able to access my routes. I keep getting error Cannot GET /api/test whenever I route to /api/test – What am I doing wrong?

routes/testRoute.js

const express = require('express');
const router = express.Router();
const { getTest } = require('../controllers/testRouteController');

router.get('/test', getTest);

router.get('/', (req, res) => {
  res.status(200).json({ message: 'Hi' });
});

module.exports = router;

controllers/testRouteController.js

const getTest = (req, res) => {
  console.log('Hello');
  res.status(200).json({ message: 'base' });
};

module.exports = {
  getTest,
};

index.js

const express = require('express');
const app = express();
const port = 3010 || 5000;

const testRoute = require('./routes/testRoute');

app.get('/api', testRoute);

app.listen(port);

Solution

You have to mount routers using app.use():

app.use('/api', testRoute);

Answered By – robertklep

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published