Search code examples
javascripthtmlnode.jsexpressejs

Can you render a plain HTML using Express JS without using Ejs or else


I have simple HTML with bootstrap Form in it and also I've Coded a simple API there, when I am requesting /about in my server.js it should redirect me to about.html page but it is giving me an error which I've also provided. I know I can use ejs or something but I want to use plain html and deal with it if possible.

This is Express js Backend Code.

import express  from "express";
import path from "path";
import { fileURLToPath } from "url"

const app = express();
const port = 3000;

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.use(express.static(__dirname + '\\public'));

app.get('/', (req, res) => {
    res.sendFile('index.html')
});

app.get('/about', (req, res) => {
    res.render('about.html');
    console.log(`Request Granted`);
});

app.listen(port, () => { console.log('App listening on port ', port)});

This is Index.html code which is inside public folder.

<script>
        const btns = document.getElementById('suc');
        const btnd = document.getElementById('dan');

        btns.addEventListener('click', async ()=>{
            let response = await fetch('http://localhost:3000/about');
            let request = await response.json();
        })
</script>

I've tried to us sendFile Here

app.get('/about', (req, res) => {
res.render('about.html'); //<-------------HERE
console.log(`Request Granted`);
});

I also tried Remedies from ChatGPT but nothing happened which I expected.


Solution

  • Plain HTML files are also valid EJS files. Just configure your view engine

    app.set('view engine', 'ejs');
    app.set('views', './views');
    

    put your index.html under './views' renamed to 'index.ejs' and render with

    res.render('index');
    

    If you really can't stand the EJS extension and you want your files to have HTML extension, just tell express you use EJS but with HTML file extension:

    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    app.set('views', './views');
    

    With this configuration, you put your index.html in ./views and render it in same way

    res.render('index');