Node JS Express JS With HTML

Node.js and Express.js are commonly used together to create dynamic web applications, and HTML is essential for structuring the web pages. Here's a quick breakdown of their roles:

  1. Node.js: JavaScript runtime environment to execute server-side code.
  2. Express.js: A minimal and flexible web framework for Node.js to handle routing, middleware, and HTTP requests.
  3. HTML: Used to design and structure the front-end of the web application.

 Server.js file ..

const express = require('express');
const path = require('path');
const app = express();

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

app.get('/api/users', (req,res) => {
    const users = [{
        id: '111',
        name:'rohit',
    },{
        id:'222',
        name:'raju',
    },{
        id:'333',
        name:'ram'
    }];
    res.json(users);
});
app.listen(8080, () => {
    console.log('Server demo on port 8080');
});

Index.html File
<!DOCTYPE html>
<html>

<head>
    <title>
        This is server and frontend linking demo
    </title>
</head>

<body>
    <h1>
        Hello Server is responding with frontend....
    </h1>
    <script>
        // // alert('hello from thefrontend');
        // console.log('hello msg on console');
        fetch('/api/users')
            .then(response => response.json())
            .then(users => console.log(users));

    </script>
</body>
</html>

Key Notes:

  • Place static assets (CSS, JS, images) in a folder like public/ and use express.static() to serve them.
  • You can use Express.js routing to add more endpoints for APIs or additional pages.
  • Integrate templating engines like EJS, Pug, or Handlebars for dynamic HTML rendering.

Let me know if you'd like to see an example of dynamic rendering with a templating engine! 🚀