kadina
kadina

Reputation: 5376

get() in node.js app is not getting called when I try to hit localhost

I am new to node.js. I have the below program called app.js running on my laptop

var express = require('express');
var engine = require('consolidate');

var app = express();

app.set('views', __dirname);
app.engine('html', engine.mustache);
app.set('view engine', 'html');

app.use(express.static('.'));

app.get('/', function(req, res) {
    console.log("Got request for index.html");
    res.render('index.html');
});

app.listen(5000, '0.0.0.0');

and I have index.html in the same path as app.js. When I tried to hit localhost:5000 from browser or from postman, I am getting index.html as response. I thought app.get() will be called and the log "Got request for index.html" will be displayed. But that function is not getting called. I understood that .get() is called for routing.

I am not sure how browser / postman is getting index.html as response if get() in app.js is not getting hit. Can any one please help me to understand how postman is getting response even though app.get() is not getting called.

Upvotes: 0

Views: 99

Answers (1)

Michael Westcott
Michael Westcott

Reputation: 480

Express middlewares are applied in order. express.static doesn't call the next middleware in the chain if it matches on a file - it just serves the file and ends the response. So because index.html is in your static files directory it means the app.get middleware is never called.

Generally you'd create a public folder for your static assets and a views folder for your HTML views.

something like:

const {join} = require('path');
app.set('views', join(__dirname, '/views'));
app.engine('html', engine.mustache);
app.set('view engine', 'mustache');
app.use(express.static(join(__dirname,'/public')));

and make sure your index.html is in the views folder and your static assets are in the public folder

Upvotes: 1

Related Questions