Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It's the most popular framework for building APIs with Node.js.
1. Setting Up Your Project
First, make sure you have Node.js installed. Create a new project folder, navigate into it, and initialize a package.json file. Then, install Express.
Bash
mkdir my-first-express-app cd my-first-express-app npm init -y npm install express
2. The "Hello World" Server
Creating a basic Express server is incredibly simple. Create a file named app.js and add the following code:
JavaScript
// 1. Import the express library
const express = require('express');
// 2. Create an instance of an Express application
const app = express();
// 3. Define the port the server will run on
const port = 3000;
// 4. Define a basic route
// This handles GET requests to the root URL ('/')
app.get('/', (req, res) => {
res.send('Hello World!');
});
// 5. Start the server and listen for incoming connections
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
To run your server, execute the following command in your terminal:
Bash
node app.js
Now, if you open your web browser and navigate to http://localhost:3000, you will see the message "Hello World!".
3. Routing Basics
Routing refers to how an application’s endpoints (URIs) respond to client requests. You define routes using methods on the app object that correspond to HTTP methods (e.g., app.get(), app.post(), app.put(), app.delete()).
Each route handler function takes two main arguments:
- req (Request): An object containing information about the incoming HTTP request, such as parameters, query strings, headers, and the request body.
- res (Response): An object used to send a response back to the client.
Here are a few more examples:
JavaScript
// A POST route to create a new user
app.post('/users', (req, res) => {
// In a real app, you'd save a user to a database here
res.status(201).json({ message: 'User created successfully', userId: 123 });
});
// A route with a URL parameter to fetch a specific book
// The ':id' is a placeholder for a dynamic value
app.get('/books/:id', (req, res) => {
const bookId = req.params.id;
res.send(`Fetching details for book with ID: ${bookId}`);
});
// A route that uses a query string
// e.g., /search?q=express
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`You searched for: "${query}"`);
});
This simple structure is the foundation of every Express application, from small projects to large-scale APIs.