Paramclasses Academy - Blog

Tutorials Details

←
Post 17 of 40
→

Express.js Tutorial: Create Your First Node.js Web Application

Express.js Tutorial: Create Your First Node.js Web Application

October 29, 2026

✦ Express.js Tutorial: Create Your First Node.js Web Application

❖ Introduction

Node.js allows developers to run JavaScript on the server, making it possible to build web applications and backend APIs using JavaScript. However, creating a complete web application using only the built-in HTTP module can require writing additional code for routing, request handling, and middleware.

Express.js is a popular web framework for Node.js that simplifies these tasks. It provides an organized way to handle HTTP requests, define routes, process request data, and send responses.

In this tutorial, we will learn how to install Express.js, create your first web application, build routes, return HTML and JSON responses, handle errors, and organize a simple Node.js project.

✦ What Is Express.js?

Express.js is a lightweight web framework built for Node.js. It helps developers build websites, backend applications, and REST APIs with less repetitive code.

Express.js is commonly used for:

  • Building REST APIs.

  • Creating backend services for websites.

  • Handling HTTP requests and responses.

  • Creating routes for different pages.

  • Processing form and JSON data.

  • Connecting applications to MySQL and MongoDB.

  • Using middleware for authentication, logging, and validation.

For example, a Node.js HTTP server requires you to handle routing and response logic manually. Express provides convenient methods such as app.get() and app.post() for defining routes.

❖ Node.js vs Express.js

Node.js Express.js
JavaScript runtime Web framework for Node.js
Executes JavaScript outside the browser Simplifies web application development
Provides built-in modules such as http Provides routing and middleware features
Can create a server without an external framework Runs on Node.js

Important: Express.js does not replace Node.js. It runs on Node.js and uses its capabilities.

✦ Step 1: Install Node.js and Create a Project

First, check that Node.js and npm are installed:

node -v
npm -v

Create a project folder:

mkdir express-first-app
cd express-first-app

Initialize the project:

npm init -y

This creates a package.json file containing project information and dependencies.

Now install Express.js:

npm install express

Express is now available for your application.

✦ Step 2: Create Your First Express.js Application

Create a file named app.js inside your project folder.

Add this complete code:

const express = require("express");

const app = express();

const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
    res.send("Welcome to Param Classes!");
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Run the application:

node app.js

Open your browser and visit:

http://localhost:3000

You should see:

Welcome to Param Classes!

Congratulations! You have created your first Express.js web application.

❖ Understanding the Code

Let's understand the important parts of the application.

1. Import Express

const express = require("express");

This loads the Express package into your application.

2. Create the application

const app = express();

The app object provides methods for defining routes, adding middleware, and configuring the server.

3. Create a GET route

app.get("/", (req, res) => {
    res.send("Welcome to Param Classes!");
});

This route handles GET requests sent to the root URL /.

Here:

  • req represents the incoming request.

  • res represents the outgoing response.

  • res.send() sends a response to the client.

4. Start the server

app.listen(PORT, () => {
    console.log("Server started");
});

The server starts listening on the configured port.

✦ Step 3: Create Multiple Routes

Most web applications contain multiple pages or endpoints. Express makes it easy to define them.

Replace your app.js code with:

const express = require("express");

const app = express();
const PORT = process.env.PORT || 3000;

app.get("/", (req, res) => {
    res.send("Home Page");
});

app.get("/about", (req, res) => {
    res.send("About Param Classes");
});

app.get("/services", (req, res) => {
    res.send("Our Services");
});

app.get("/contact", (req, res) => {
    res.send("Contact Us");
});

app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Test these URLs in your browser:

URL Response
/ Home Page
/about About Param Classes
/services Our Services
/contact Contact Us

This is basic routing. Each route responds to a particular URL and HTTP method.

✦ Step 4: Send HTML Responses

Express can send HTML directly to the browser.

const express = require("express");

const app = express();

app.get("/", (req, res) => {
    res.send(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Param Classes</title>
        </head>
        <body>
            <h1>Welcome to Param Classes</h1>
            <p>Learn Node.js and Express.js with practical examples.</p>
        </body>
        </html>
    `);
});

app.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

When you open the root URL, the browser renders the HTML page.

For larger websites, it is usually better to keep HTML in separate files or use a template engine instead of placing all markup inside route handlers.

✦ Step 5: Create a JSON API

Express.js is widely used for building APIs that return data to frontend applications and mobile apps.

Create an API that returns student records:

const express = require("express");

const app = express();

const students = [
    { id: 1, name: "Rahul", course: "Node.js" },
    { id: 2, name: "Priya", course: "JavaScript" },
    { id: 3, name: "Amit", course: "PHP" }
];

app.get("/api/students", (req, res) => {
    res.json({
        success: true,
        data: students
    });
});

app.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Visit:

http://localhost:3000/api/students

The server returns JSON data similar to:

{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "Rahul",
            "course": "Node.js"
        },
        {
            "id": 2,
            "name": "Priya",
            "course": "JavaScript"
        },
        {
            "id": 3,
            "name": "Amit",
            "course": "PHP"
        }
    ]
}

This example stores data in an array. The records will reset whenever the application restarts. A production application would typically use a database.

✦ Step 6: Handle POST Requests and JSON Data

A POST request is commonly used to submit data or create a resource.

Express provides express.json() middleware to parse incoming JSON request bodies.

Add the following code to app.js:

const express = require("express");

const app = express();

app.use(express.json());

app.post("/api/students", (req, res) => {
    const { name, course } = req.body;

    if (
        typeof name !== "string" ||
        !name.trim() ||
        typeof course !== "string" ||
        !course.trim()
    ) {
        return res.status(400).json({
            success: false,
            message: "Valid name and course are required"
        });
    }

    res.status(201).json({
        success: true,
        message: "Student data received",
        data: {
            name: name.trim(),
            course: course.trim()
        }
    });
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Test this endpoint using Postman or another API client.

  • Method: POST

  • URL: http://localhost:3000/api/students

  • Body type: raw → JSON

Request body:

{
    "name": "Rahul",
    "course": "Node.js"
}

Expected response:

{
    "success": true,
    "message": "Student data received",
    "data": {
        "name": "Rahul",
        "course": "Node.js"
    }
}

This example validates basic input and returns the received data. It does not save a student record permanently. For persistent storage, connect the route to a database.

✦ Step 7: Understand Middleware in Express.js

Middleware functions run during the request-response process. They can inspect or modify the request, perform authentication, log information, and pass control to the next middleware or route handler.

Example of custom logging middleware:

const express = require("express");

const app = express();

app.use((req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
});

app.get("/", (req, res) => {
    res.send("Welcome to Express.js");
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Whenever a request reaches the server, the middleware logs the HTTP method and URL.

The next() function passes control to the next middleware or route handler. If middleware neither sends a response nor calls next(), the request may remain unfinished.

✦ Step 8: Handle 404 Errors

When no route matches a request, you can return a custom 404 response.

Add this after your application's routes:

app.use((req, res) => {
    res.status(404).json({
        success: false,
        message: "Page not found"
    });
});

Place this middleware after the routes so it handles requests that did not match any of them.

For example, visiting /unknown-page will return a JSON response with status code 404.

✦ Common Mistakes Beginners Should Avoid

❖ Forgetting to install Express: Run npm install express before starting the application.

❖ Using the wrong URL or HTTP method: A GET route does not automatically handle POST requests.

❖ Forgetting express.json(): Without this middleware, req.body may not contain parsed JSON data.

❖ Ignoring input validation: Always validate user-submitted data before processing or saving it.

❖ Forgetting next() in middleware: If middleware does not finish the response or pass control onward, the request can hang.

❖ Keeping all logic in one file: Separate routes, controllers, services, and database operations as your project grows.

❖ Assuming an API response saves data: Sending JSON to a client does not automatically store it in a database.

✦ Frequently Asked Questions (FAQs)

1. What is Express.js in Node.js?

Express.js is a web framework for Node.js that simplifies routing, middleware, request handling, and response generation.

2. Is Express.js a programming language?

No. Express.js is a JavaScript framework that runs on Node.js.

3. Do I need to install Express separately?

Yes. In a typical project, install it using npm install express.

4. What is routing in Express.js?

Routing defines how an application responds to requests for specific URLs and HTTP methods.

5. What is middleware in Express.js?

Middleware is a function that runs during request processing and can perform tasks such as logging, authentication, validation, and error handling.

6. Can Express.js connect to MySQL?

Yes. Express routes can use a MySQL driver or database library to query and update database records.

✦ Conclusion

Express.js makes Node.js web development more organized by providing convenient routing, middleware, and request-response methods. By building your first application, creating multiple routes, returning JSON, and handling POST requests, you will develop a solid foundation for backend development.

Next, practise connecting your Express application to MySQL and building a complete CRUD API.

Keep learning and keep building with Param Classes!

←
Post 17 of 40
→