Why Use Node.js and Express?¶
Node.js is a JavaScript runtime environment built on Chrome’s V8 engine, allowing us to write JavaScript code on the server side. Express, the most popular web framework for Node.js, acts like a “scaffold” to help us quickly build web servers, handle routes, requests, and responses—making it much simpler than using Node.js’s native APIs directly.
Environment Setup: Install Node.js and npm¶
Before starting, we need to install Node.js (which includes the npm package manager).
- Download and Install Node.js:
Visit the Node.js official website, download the LTS (Long-Term Support) version, and install it. After installation, open your terminal (Command Prompt or PowerShell for Windows users) and run these commands to verify:
node -v # Check Node.js version
npm -v # Check npm version
If version numbers are displayed, the installation is successful.
Step 1: Create a Project and Install Express¶
- Create a Project Folder:
Navigate to your preferred location (e.g., Desktop) and create a new folder namedmy-first-express-server, then enter it:
mkdir my-first-express-server
cd my-first-express-server
- Initialize the Project:
Runnpm init -yto quickly generate a defaultpackage.jsonfile (project configuration):
npm init -y
- Install the Express Framework:
Execute the following command to install Express in your project:
npm install express
After installation, you’ll see a node_modules folder and an updated package.json with a dependencies field listing Express’s version.
Step 2: Write Your First Web Server¶
Create a server.js file in the project folder (this is the entry point for your server) and copy the following code:
// 1. Import the Express module
const express = require('express');
// 2. Create an Express application instance
const app = express();
// 3. Define the port number (3000 is a common development port to avoid conflicts)
const port = 3000;
// 4. Define a route: Handle GET requests to the root path '/'
app.get('/', (req, res) => {
// req: Request object, contains client information (e.g., path, parameters)
// res: Response object, used to send data back to the client
res.send('Hello, this is my first Express server!');
});
// 5. Start the server and listen on the specified port
app.listen(port, () => {
console.log(`Server started at: http://localhost:${port}`);
});
Code Explanation¶
const express = require('express'): Import the Express framework from Node.js’s module system, “grabbing” the Express tool.const app = express(): Create an Express application instance. Theappobject is the core of your application, used to define routes, middleware, etc.app.get('/', (req, res) => { ... }): Define a route rule: When a client sends a GET request to the root path'/', the function inside the parentheses executes.'/'is the request path;app.gethandles only GET requests (other methods likeapp.postorapp.puthandle different HTTP methods).req(Request) contains client data (e.g., URL parameters, headers, query strings).res(Response) is used to send data back to the client (text, HTML, JSON, etc.).res.send(...): Sends data to the client (here, a simple text string).app.listen(port, ...): Starts the server and listens on the specifiedport(3000). When the server starts successfully, the callback function runs to print a confirmation message.
Run the Server¶
In the terminal within your project folder, run:
node server.js
If the console shows Server started at: http://localhost:3000, the server is running successfully!
Test the Server¶
Open your browser and visit http://localhost:3000. You’ll see the message: Hello, this is my first Express server!. Great! You’ve built your first simple web server.
Extension: Add More Routes¶
Express’s core is routing. You can handle different requests with various paths and HTTP methods. For example, add an “About” page and a “User” page:
// Root path
app.get('/', (req, res) => {
res.send('<h1>Home Page</h1>'); // Can return HTML directly
});
// About page
app.get('/about', (req, res) => {
res.send('This is the About page. Welcome to learn more!');
});
// User page (dynamic route parameter)
app.get('/user/:id', (req, res) => {
// req.params.id captures dynamic values (e.g., /user/123 → id=123)
res.send(`User ID: ${req.params.id}`);
});
Restart the server and visit http://localhost:3000/about or http://localhost:3000/user/456 to see different content!
Handling JSON Data and Static Files¶
1. Return JSON Data¶
To return JSON (e.g., for an API), use res.json():
app.get('/api/data', (req, res) => {
const data = {
name: 'Node.js',
framework: 'Express',
version: '4.x'
};
res.json(data); // Automatically sets Content-Type to application/json
});
Visit http://localhost:3000/api/data to see the JSON object.
2. Serve Static Files (HTML/CSS/JS)¶
To host static resources (e.g., an HTML/CSS/JS project), use Express’s built-in middleware express.static:
- Create a
publicfolder in your project root and place static files (e.g.,index.html):
my-first-express-server/
├─ public/
│ └─ index.html
└─ server.js
- Update
server.jsto include:
const path = require('path'); // Import Node.js path module for path handling
app.use(express.static(path.join(__dirname, 'public'))); // Serve static files from the 'public' folder
Now, visit http://localhost:3000/index.html to access the static index.html file.
Summary¶
In this article, you’ve learned the basic steps to build a web server with Express:
1. Install Node.js and Express.
2. Create and initialize a project.
3. Define routes to handle requests.
4. Start and test the server.
5. Extend functionality (e.g., return JSON, serve static files).
Express’s core is “routing + middleware”. Next, explore middleware (e.g., error handling, logging), dynamic route parameters, and form submission. Try modifying the code to create your own routes or pages!