đ Introduction
After installing Express.js, the next step is to create a basic web server. An Express server listens for incoming HTTP requests, processes them through routes and middleware, and sends appropriate responses back to the client. With just a few lines of code, you can build a functional web server using Node.js and Express.js.
Information
đ Prerequisites
- Node.js installed on your system.
- Express.js installed using npm install express.
- A project initialized with package.json.
- A code editor such as Visual Studio Code.
đ Steps to Create an Express Server
đ Project Structure
đ Creating the Express Server
index.js
const express = require('express');
// Create an Express application
const app = express();
// Define the port number
const PORT = 3000;
// Define a route
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});âļī¸ Running the Server
Start the Server
node index.jsOnce the server starts successfully, open your browser and navigate to http://localhost:3000. You should see the message "Welcome to Express.js!".
Success
đ Understanding the Code
| Code | Purpose |
|---|---|
| require('express') | Imports the Express framework. |
| express() | Creates a new Express application instance. |
| app.get() | Registers a route for HTTP GET requests. |
| req | Represents the incoming HTTP request. |
| res | Represents the HTTP response sent to the client. |
| app.listen() | Starts the server and listens for incoming requests. |
đŖ Adding Multiple Routes
Multiple Routes Example
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.get('/contact', (req, res) => {
res.send('Contact Page');
});Each route is associated with a specific URL path. When a client requests that path using the appropriate HTTP method, Express executes the corresponding route handler.
đ Express Request Lifecycle
âī¸ Using a Custom Port
Using Environment Variables
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});Best Practice
đ Common Server Methods
| Method | Description |
|---|---|
| app.get() | Handles HTTP GET requests. |
| app.post() | Handles HTTP POST requests. |
| app.put() | Handles HTTP PUT requests. |
| app.delete() | Handles HTTP DELETE requests. |
| app.listen() | Starts the Express server. |
đĄ Best Practices
- Keep the server entry file simple and organized.
- Use meaningful route names.
- Store the port number in an environment variable whenever possible.
- Separate routes, controllers, and middleware into different folders as the project grows.
- Handle server errors gracefully in production applications.
đ Learn More
Explore the official documentation for more details:
âĸ Express.js Official Documentation
âĸ Node.js Documentation