Build a Full-Featured Node.js Web Server with Express: Step‑by‑Step Guide

This tutorial walks you through installing Node.js and npm, initializing a project, adding Express, creating routes, handling static files, processing POST requests with body‑parser, implementing simple in‑memory storage, adding error handling, and rendering HTML with EJS, all illustrated with complete code examples.

21CTO
21CTO
21CTO
Build a Full-Featured Node.js Web Server with Express: Step‑by‑Step Guide

Node.js is an open‑source, cross‑platform JavaScript runtime that lets developers build server‑side applications outside the browser.

In this practical guide you will learn how to create a web server using Node.js and Express.

Key points

Implement a simple Node.js web server with project initialization, Express integration and basic features.

Build dynamic web applications handling forms, user requests and dynamic page rendering.

Explore Node.js web development capabilities such as static file handling, error handling and form submission.

Part 1: Project setup and installation

Step 1: Install Node.js and npm

Download and install Node.js from the official website; npm is included as the package manager.

Verify installation:

node -v</code><code>npm -v

Step 2: Initialize a new Node.js project

mkdir book-club</code><code>cd book-club</code><code>npm init -y

The generated package.json contains project metadata.

Step 3: Install Express.js

npm install express

Part 2: Set up the Express server

Step 1: Create a new file app.js

This file will hold the Express server code.

Step 2: Import Express

const express = require('express');

Step 3: Create the Express application

const app = express();

The express() function creates the app instance.

Step 4: Define routes

app.get('/', (req, res) => {</code><code>  res.send('Hello World!');</code><code>});

This route responds with a simple message.

Step 5: Start the server

const port = 3000;</code><code>app.listen(port, () => {</code><code>  console.log(`Server is running at http://localhost:${port}`);</code><code>});

Part 3: Build application functionality

Step 1: Create a messages file

module.exports = {</code><code>  home: 'Welcome to our Book Club!',</code><code>  about: 'About Us',</code><code>  notFound: '404 Not Found'</code><code>};

Step 2: Import messages in app.js

const messages = require('./messages');

Step 3: Use messages in routes

app.get('/', (req, res) => {</code><code>  res.send(messages.home);</code><code>});</code><code>app.get('/about', (req, res) => {</code><code>  res.send(messages.about);</code><code>});</code><code>app.use((req, res) => {</code><code>  res.status(404).send(messages.notFound);</code><code>});

Part 4: Add static file serving

Step 1: Create a public directory

mkdir public

Step 2: Add static files (e.g., index.html and styles.css )

<!DOCTYPE html></code><code><html></code><code><head></code><code>  <title>Book Club</title></code><code>  <link rel="stylesheet" type="text/css" href="/styles.css"></code><code></head></code><code><body></code><code>  <h1>Welcome to our Book Club!</h1></code><code></body></code><code></html>
body {</code><code>  font-family: Arial, sans-serif;</code><code>}

Step 3: Use express.static middleware

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

Part 5: Handle POST requests

Step 1: Add a form to index.html

<form action="/submit" method="post"></code><code>  <input type="text" name="book" placeholder="Enter a book title"></code><code>  <button type="submit">Submit</button></code><code></form>

Step 2: Install body-parser

npm install body-parser

Step 3: Import and use body-parser

const bodyParser = require('body-parser');</code><code>app.use(bodyParser.urlencoded({ extended: false }));

Step 4: Process the POST request

app.post('/submit', (req, res) => {</code><code>  const book = req.body.book;</code><code>  console.log(`Book submitted: ${book}`);</code><code>  res.send(`Book submitted: ${book}`);</code><code>});

Part 6: Add data storage

Step 1: Create an in‑memory array

const books = [];

Step 2: Update POST handler to store books

app.post('/submit', (req, res) => {</code><code>  const book = req.body.book;</code><code>  books.push(book);</code><code>  console.log(`Book submitted: ${book}`);</code><code>  res.send(`Book submitted: ${book}`);</code><code>});

Step 3: Add a route to view all books

app.get('/books', (req, res) => {</code><code>  res.send(books.join(', '));</code><code>});

Note: In a real application you would use a database; the array is cleared when the server restarts.

Part 7: Add error handling

Step 1: Create error‑handling middleware

app.use((err, req, res, next) => {</code><code>  console.error(err.stack);</code><code>  res.status(500).send('Something Went Wrong!');</code><code>});

Step 2: Pass errors with next

app.post('/submit', (req, res, next) => {</code><code>  const book = req.body.book;</code><code>  if (!book) {</code><code>    return next(new Error('Book title is required'));</code><code>  }</code><code>  books.push(book);</code><code>  res.send(`Book submitted: ${book}`);</code><code>});

Part 8: Render HTML pages with EJS

Step 1: Install EJS

npm install ejs

Step 2: Set EJS as the view engine

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

Step 3: Create a views directory and an index.ejs template

<!DOCTYPE html></code><code><html></code><code><head></code><code>    <title>Book Club</title></code><code></head></code><code><body></code><code>    <h1><%= message %></h1></code><code>    <form action="/submit" method="post"></code><code>        <input type="text" name="book" placeholder="Enter a book title"></code><code>        <button type="submit">Submit</button></code><code>    </form></code><code>    <h2>Submitted Books:</h2></code><code>    <ul></code><code>        <% books.forEach(function(book) { %></code><code>            <li><%= book %></li></code><code>        <% }); %></code><code>    </ul></code><code></body></code><code></html>

Step 4: Update routes to use EJS

app.get('/', (req, res) => {</code><code>  res.render('index', { message: messages.home, books: books });</code><code>});
app.post('/submit', (req, res) => {</code><code>  const book = req.body.book;</code><code>  books.push(book);</code><code>  console.log(`Book submitted: ${book}`);</code><code>  res.redirect('/');</code><code>});

Conclusion

Congratulations! You have built a complete Node.js and Express web application featuring static file serving, dynamic routes, middleware, simple data storage, error handling, and EJS templating. The platform can be extended with databases, APIs, WebSockets and more.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptBackend DevelopmentNode.jsWeb serverTutorialExpress
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.