Home > Software design >  Getting "Cannot GET /" on the front page with Express.js
Getting "Cannot GET /" on the front page with Express.js

Time:07-31

I am new to Node.js. After watching many explanatory videos and and reading the Node.js 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 :

'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.

CodePudding user response:

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;
  • Related