Express Hello World
Introduction
Creating a "Hello World" application is a traditional first step when learning a new programming framework or language. In this lesson, we'll build our first Express.js application - a simple web server that responds with "Hello World" when accessed through a web browser. This will provide a foundational understanding of how Express works and how it handles HTTP requests.
Express.js is a minimal, flexible web application framework for Node.js that simplifies the process of building web applications and APIs. It provides a set of features for developing web and mobile applications, making server-side development with Node.js much more manageable.
Prerequisites
Before we begin, make sure you have:
- Node.js installed on your computer (version 12.x or later recommended)
- Basic knowledge of JavaScript
- A text editor or IDE (like VS Code, Sublime Text, etc.)
- Terminal or command prompt access
Setting Up Your First Express Application
Let's start by creating a new project directory and initializing it with npm:
mkdir my-express-app
cd my-express-app
npm init -y
Next, install Express as a dependency:
npm install express
Creating Your First Express Server
Now, let's create the main file for our application. Create a new file called app.js
or index.js
in your project directory:
// Import the express module
const express = require('express');
// Create an Express application
const app = express();
// Define the port the app will run on
const PORT = 3000;
// Define a route for the root URL
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Understanding the Code
Let's break down what each part of the code does:
-
Import Express:
const express = require('express');
imports the Express.js framework. -
Create an Express Application:
const app = express();
creates a new Express application. Thisapp
object is the main interface for configuring and operating your Express server. -
Define a Port:
const PORT = 3000;
sets the port number on which our server will listen for incoming connections. -
Define a Route:
javascriptapp.get('/', (req, res) => {
res.send('Hello World!');
});This creates a route handler for GET requests to the root path (
/
). When someone visits our website's homepage, this function will execute.req
is the request object containing information about the incoming HTTP requestres
is the response object used to send back data to the clientres.send('Hello World!');
sends the text "Hello World!" as the response
-
Start the Server:
javascriptapp.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});This starts the server on the specified port and executes the callback function when the server is successfully started.
Running Your First Express App
To run your application, go to your terminal and execute:
node app.js
You should see the following output:
Server is running on http://localhost:3000
Now, open your web browser and navigate to http://localhost:3000. You should see "Hello World!" displayed in your browser.
Congratulations! You've just created your first Express.js application.
Adding More Routes
Let's expand our application by adding a few more routes:
// Import the express module
const express = require('express');
// Create an Express application
const app = express();
// Define the port the app will run on
const PORT = 3000;
// Define a route for the root URL
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Add a route for /about
app.get('/about', (req, res) => {
res.send('This is a simple Express application.');
});
// Add a route with parameters
app.get('/user/:name', (req, res) => {
const userName = req.params.name;
res.send(`Hello, ${userName}!`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
With this extended code, you can now visit:
- http://localhost:3000/ - Shows "Hello World!"
- http://localhost:3000/about - Shows "This is a simple Express application."
- http://localhost:3000/user/John - Shows "Hello, John!" (you can replace "John" with any name)
Serving HTML Content
Instead of just sending plain text, you can also send HTML content:
app.get('/html', (req, res) => {
res.send(`
<html>
<head>
<title>Express Hello World</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
h1 {
color: #333;
}
</style>
</head>
<body>
<h1>Hello World from Express!</h1>
<p>This is HTML content served via Express.js</p>
</body>
</html>
`);
});
Sending JSON Responses
Express makes it easy to send JSON responses, which are commonly used when building APIs:
app.get('/api/info', (req, res) => {
res.json({
appName: 'My First Express App',
version: '1.0.0',
author: 'Your Name',
features: ['Simple routing', 'HTTP server', 'JSON responses']
});
});
Real-World Application: A Simple API
Let's expand our application to create a simple API that manages a list of items:
// Import the express module
const express = require('express');
// Create an Express application
const app = express();
// Enable parsing of JSON bodies
app.use(express.json());
// Sample data
let items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
// Get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// Get a single item by ID
app.get('/api/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = items.find(item => item.id === id);
if (!item) {
return res.status(404).json({ message: 'Item not found' });
}
res.json(item);
});
// Add a new item
app.post('/api/items', (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).json({ message: 'Name is required' });
}
const newItem = {
id: items.length > 0 ? Math.max(...items.map(item => item.id)) + 1 : 1,
name
};
items.push(newItem);
res.status(201).json(newItem);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
This API allows:
- Getting all items via GET
/api/items
- Getting a specific item via GET
/api/items/:id
(e.g.,/api/items/1
) - Creating a new item via POST
/api/items
with a JSON body like{"name": "New Item"}
To test this API, you can use tools like Postman or cURL.
Summary
In this lesson, you learned:
- How to set up a basic Express.js application
- Creating a simple "Hello World" server
- Defining routes for different URL paths
- Handling route parameters
- Sending different types of responses (text, HTML, JSON)
- Creating a simple RESTful API
Express.js provides a clean, minimal framework for building web applications and APIs with Node.js. This "Hello World" example serves as a foundation for understanding more complex Express applications.
Additional Resources
- Express.js Official Documentation
- MDN Web Docs: Express/Node Introduction
- Express.js GitHub Repository
Exercises
-
Basic Route Challenge: Add a new route
/contact
that displays contact information. -
Query Parameters: Create a route that accepts query parameters (e.g.,
/greet?name=John
) and responds with a personalized greeting. -
Advanced API: Extend the items API to support updating (PUT) and deleting (DELETE) items.
-
Static Files: Learn how to serve static files like CSS, images, or client-side JavaScript using
express.static
. -
Middleware: Implement a simple logging middleware that logs all incoming requests to the console.
These exercises will help reinforce your understanding of Express.js basics and prepare you for more advanced topics.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)