Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting "Cannot GET /" on the front page with express.js

I am new to Node.js. After watching many explanatory videos and Node docs, I started developing the site while respecting an MVC structure. The node server seems to work but the display on the front shows Cannot GET /. Here is the Browser Screenshot and the MVC structure of the project

index.js code :

'use strict';
/* eslint-env node, es6 */

const express = require('express');
const app = express();
app.set('view engine', 'ejs');

const PORT = process.env.PORT || 4242;

app.use('/', require('./routes/home_route'));

app.listen(PORT, () => {
    console.log(`serveur démaré: localhost:${PORT}`);
});

home_controller.js code :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'use strict';

const homeView = (req, res) => {
    res.render("home_view", {
    } );
}
module.exports =  { homeView };

home_route.js code :

'use strict';

const express = require('express');
const { homeView } = require('../controllers/home_controller');
const router = express.Router();
router.get('/home', homeView);
module.exports = router;

And home_view.ejs is just html. I don’t understand where my mistake is, the code seems correct to me. Thank you in advance for your answers.

>Solution :

The problem is that you don’t have any route handler for /. You are only handling /home. What you are saying with this line app.use('/', require('./routes/home_route')); is that every time I receive a request on /, I passe it to that router inside home_route.js, which only handles /home.

One way to solve this is to redirect the request you get on / to /home which is already handled. For that change home_route.js to:

const express = require('express');
const { homeView } = require('../controllers/home_controller');
const router = express.Router();
router.get('/home', homeView);
router.get('/', (req, res)=> res.redirect('/home')); // line I added
module.exports = router;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading