All posts
APIExpressTypeScriptJavaScriptProgrammingHTMLCSS

Building Web Applications from Scratch - Part 1: Introduction to Web Servers with Express

Paul Allies
Building Web Applications from Scratch - Part 1: Introduction to Web Servers with Express

Introduction

For a new developer, understanding the need for a web server is essential. Initially, you might have created simple static web pages using just HTML, CSS, and JavaScript. Web servers play a crucial role in delivering these static files to users. However, modern web applications often require dynamic content, user interaction, and data processing, which cannot be handled by static pages alone. This is where web servers with dynamic capabilities come into play.

In this first part of our blog series, we’ll introduce you to building a basic web application server using Express.js, a popular web framework for Node.js. We’ll also explain how web servers serve both static and dynamic content and why dynamic HTML generation is useful.

Why Do We Need a Web Server?

A web server can serve both static files (like HTML, CSS, and JavaScript) and dynamic content. Static websites display the same content to every user, which is fine for simple sites but limiting for applications that require user interaction, data fetching, or personalized experiences. A web server allows us to:

  • Serve static files like HTML, CSS, and JavaScript.
  • Process user requests dynamically.
  • Generate and serve different content based on user input.
  • Handle forms and user interactions.
  • Interact with databases and external APIs.
  • Maintain session states and authentication.

Setting Up a Basic Web Server with Express.js

To get started, ensure you have Node.js installed on your system.

Step 1: Initialize a Node.js Project

First, create a new project folder and initialize it:

mkdir my-web-app
cd my-web-app
npm init -y

This creates a package.json file to manage dependencies.

Step 2: Install Express.js

Express.js is a lightweight framework for building web applications with Node.js. Install it by running:

npm install express

Step 3: Create a Basic Web Server

Create a new file called server.js and add the following code:

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

// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
    res.send('<h1>Welcome to My Web App</h1><p>This is a dynamic web page generated by Express.</p>');
});

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

Step 4: Run the Server

Start the server by running:

node server.js

Now, open your browser and navigate to http://localhost:3000. You should see your first dynamically generated web page.

Serving Static and Dynamic Content

Unlike static HTML files, which remain the same for every user, web servers like Express can dynamically generate HTML based on requests. However, web servers also serve static files efficiently. For example, if you place an index.html file inside a public folder, Express will serve it automatically without requiring additional routing.

Example: Handling Forms with Express

Let’s modify our server to handle form submissions. Create an index.html file in a public folder with the following content:

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <h1>Submit Your Name</h1>
    <form action="/submit" method="POST">
        <input type="text" name="name" required>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Modify server.js to serve this static file and handle form submissions:

const bodyParser = require('express');
app.use(express.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
    const name = req.body.name;
    res.send(`<h1>Hello, ${name}!</h1><p>Thank you for submitting the form.</p>`);
});

Restart your server, fill out the form, and see the response.

Conclusion

In this first part, we introduced the role of web servers in serving both static and dynamic content. We explained how Express can be used to serve static files and generate dynamic responses. We also built a basic Express server and demonstrated handling forms.

In the next part, we’ll explore templating engines to make HTML generation even more powerful. Stay tuned!