Search code examples
javascriptnode.jsexpresspug

res.redirect not working when using no template


I was making a project using express generator with the --no-view flag, and when I tried to redirect the response to a website (for example : www.google.com) it didn't work (code below) :

router.get('/', function(req, res, next) {
res.redirect('https://www.google.com')
});

The above code actually rendered the index.html (default) so I tried to reproduce the same issue this time using a template engine like pug, but this time the redirect worked.

My question is why when using no template engine the / route always renders index.html no matter what code I put inside ?


Solution

  • index.html file is served by following line because the project is created without view (and due to this, app.js wouldn't have code related to setting-up the view engine).

    app.use(express.static(path.join(__dirname, "public")));
    

    As per documentation, by default index file of the specified directly is going to be served. You can disable it by making index to false as follow.

    app.use(express.static(path.join(__dirname, "public"), { index: false }));