1. What is Express.js?
Express.js is a lightweight and flexible web framework built on top of Node.js. It simplifies the process of creating web applications and APIs by providing ready-to-use tools for handling HTTP requests, managing routes, and processing data. Think of Express as a toolbox that makes it easier to build a website or a backend server without writing complex Node.js code from scratch.
Why is it useful?
It saves time by providing shortcuts for common tasks like routing and middleware. It’s widely used for building RESTful APIs (e.g., for mobile apps) and web applications. It has a huge community, so you can find plenty of tutorials and plugins.
📦 Example: Imagine you want to create a website where users can visit different pages (like a homepage or about page). Express makes it easy to define what happens when users visit those pages without needing to handle low-level server details.
2. How do you install Express.js?
To use Express.js, you need to install it in your Node.js project using npm (Node Package Manager). This adds Express to your project so you can use its features.
🔹 Steps to Install:
- Create a project folder and navigate to it:
mkdir my-express-app
cd my-express-app
- Initialize a Node.js project (creates a
package.json
file):
npm init -y
- Install Express.js:
npm install express
- This command downloads Express and adds it to your project’s node_modules folder. It also updates package.json to list Express as a dependency.
📦 Example:
After running npm install express
, you can verify it’s installed by checking package.json. You’ll see something like:
"dependencies": {
"express": "^4.18.2"
}
Now you’re ready to use Express in your code!
3. How do you create a basic Express server?
Creating a basic Express server involves setting up a Node.js application that listens for HTTP requests and sends responses. Here’s a step-by-step breakdown of how to do it.
📦 Code Example:
// 1. Import the Express module
const express = require("express");
// 2. Create an Express application
const app = express();
// 3. Define a port number for the server
const port = 3000;
// 4. Create a route for the homepage (GET request)
app.get("/", (req, res) => {
res.send("Hello, this is my first Express server!");
});
// 5. Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Explanation:
- Line 1: Imports Express so you can use its features.
- Line 2: Creates an instance of an Express app, which is the core of your server.
- Line 3: Sets the port (3000 is common for development).
- Line 4: Defines a route for the root URL (/) that responds to GET requests with a simple message.
- Line 5: Starts the server, making it listen for requests on http://localhost:3000 .
How to Run:
- Save the code in a file named app.js.
- Run node app.js in your terminal.
- Open a browser and go to http://localhost:3000 . You’ll see: Hello, this is my first Express server!
4. What is routing in Express?
Routing in Express is the process of determining how your application responds to client requests for specific URLs and HTTP methods (like GET or POST). Each route maps a URL pattern and HTTP method to a specific function that handles the request.
Why is routing important?
It organizes your app by defining what content or action corresponds to each URL. For example, visiting /about might show an “About Us” page, while /contact shows a contact form.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
// Route for homepage
app.get("/", (req, res) => {
res.send("Welcome to the homepage!");
});
// Route for about page
app.get("/about", (req, res) => {
res.send("This is the about page.");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
When a user visits http://localhost:3000/ , the server responds with “Welcome to the homepage!”. When they visit http://localhost:3000/about , it responds with “This is the about page.”. Express matches the URL and HTTP method (GET in this case) to the correct route.
5. What is middleware in Express?
Middleware in Express is like a middleman that processes requests before they reach your route handlers or after they leave them. It’s a function that has access to the req (request), res (response), and next (a function to pass control to the next middleware or route). Middleware can:
Modify the request or response (e.g., add data to req). Perform tasks like logging, authentication, or parsing data. End the request-response cycle or pass control to the next middleware.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
// Middleware to log request details
app.use((req, res, next) => {
console.log(`Received a ${req.method} request to ${req.url}`);
next(); // Pass control to the next middleware or route
});
// Route
app.get("/", (req, res) => {
res.send("Hello from the server!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
The middleware logs the HTTP method (e.g., GET) and URL (e.g., /) for every request.
next()
ensures the request moves to the route handler.
When you visit http://localhost:3000 , the console logs: Received a GET request to /
, and the browser shows: Hello from the server!.
6. How do you use middleware in Express?
In Express, middleware is added using the app.use()
function or by specifying it for specific routes. Middleware can be applied globally (for all requests) or to specific routes. The express.json()
middleware, for example, parses incoming JSON data so you can access it in req.body
.
🔹 Steps to Use Middleware:
Define or import the middleware.
Use app.use()
to apply it globally or pass it to a specific route.
Ensure the middleware calls next()
if it should pass control to the next handler.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
// Use built-in middleware to parse JSON
app.use(express.json());
// Custom middleware to log request time
app.use((req, res, next) => {
console.log(`Request received at: ${new Date().toISOString()}`);
next();
});
// Route to handle POST request
app.post("/data", (req, res) => {
console.log("Received data:", req.body);
res.send("Data received!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
app.use(express.json())
: Parses JSON data sent in POST requests.
Custom middleware logs the time of each request.
The /data
route logs the JSON data sent in the request body.
Test it using a tool like Postman: Send a POST request to http://localhost:3000/data with JSON like {"name": "John"}
. The console shows the data, and the browser shows “Data received!“.
7. What are route parameters?
Route parameters are dynamic parts of a URL that you define using a colon (:
) in your route path. They allow you to capture values from the URL and use them in your route handler. For example, /users/:id
captures the id
value from the URL and makes it available in req.params
.
Why use route parameters?
- They make routes flexible, allowing you to handle dynamic data (e.g., user IDs, product IDs).
- Common for APIs or pages that display specific data. Example:
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
app.get("/users/:id", (req, res) => {
const userId = req.params.id; // Get the :id value from the URL
res.send(`You requested user with ID: ${userId}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
Visiting http://localhost:3000/users/123 shows: You requested user with ID: 123
.
Visiting http://localhost:3000/users/abc shows: You requested user with ID: abc
.
The :id
in the route captures whatever value is in that part of the URL and stores it in req.params.id
.
8. How do you handle POST requests in Express?
POST requests are used to send data to the server, such as form submissions or API data. In Express, you handle POST requests using app.post()
and often use the express.json()
middleware to parse incoming JSON data.
🔹 Steps:
- Use
app.use(express.json())
to parse JSON data. - Define a route with
app.post()
to handle the POST request. - Access the sent data in
req.body
and send a response.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
// Middleware to parse JSON
app.use(express.json());
// Handle POST request
app.post("/users", (req, res) => {
const user = req.body; // Get data from request body
res.send(`User ${user.name} created successfully!`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
- Send a POST request to http://localhost:3000/users with JSON like
{"name": "Alice"}
(use Postman or curl). - The server reads the JSON data (
req.body
) and responds with:User Alice created successfully!
. - Without
express.json()
,req.body
would be undefined.
9. What is express.json()?
express.json()
is a built-in Express middleware that parses incoming requests with JSON payloads. It takes the JSON data sent in the request body (e.g., from a form or API call) and converts it into a JavaScript object, making it available in req.body
.
Why is it needed?
- Many POST or PUT requests send data in JSON format.
- Without
express.json()
, you can’t easily access this data.
const express = require("express");
const app = express();
const port = 3000;
// Enable JSON parsing
app.use(express.json());
app.post("/submit", (req, res) => {
const data = req.body; // Access JSON data
res.send(`Received: ${data.message}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
- Send a POST request to http://localhost:3000/submit with JSON:
{"message": "Hello"}
. - The
express.json()
middleware parses the JSON, soreq.body.message
is “Hello”. - The server responds:
Received: Hello
.
10. What is req.body?
req.body
is an object in Express that contains data sent by the client in the body of a request, typically in POST or PUT requests. This data could come from HTML forms, JSON payloads, or other sources. To use req.body
, you need middleware like express.json()
or express.urlencoded()
to parse the data.
Why is it useful?
- It lets you access user-submitted data, like form inputs or API data.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
// Middleware to parse JSON
app.use(express.json());
app.post("/signup", (req, res) => {
const { username } = req.body; // Access data from request body
res.send(`Welcome, ${username}!`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
- Send a POST request to http://localhost:3000/signup with JSON:
{"username": "Bob"}
. - The
express.json()
middleware parses the JSON,so req.body.username
is “Bob”. - The server responds:
Welcome, Bob!
.
11. What is req.params?
req.params
is an object in Express that holds the values of route parameters (dynamic parts of the URL defined with a colon, :
). These parameters allow you to capture specific values from the URL to use in your route handler.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
app.get("/books/:bookId", (req, res) => {
const bookId = req.params.bookId; // Get the :bookId value
res.send(`You requested book ID: ${bookId}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
- The route
/books/:bookId
matches URLs like/books/123
or/books/abc
. - Visiting http://localhost:3000/books/123 sets
req.params.bookId
to “123”. - The server responds:
You requested book ID: 123
.
12. What is req.query?
req.query
is an object in Express that contains key-value pairs from the query string in a URL. The query string is the part of the URL after a ?, where parameters are written as key=value pairs, separated by &.
Why use it?
Query parameters are often used for filtering, searching, or passing optional data (e.g., search terms, page numbers).
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
app.get("/search", (req, res) => {
const searchTerm = req.query.q; // Get the 'q' query parameter
res.send(`You searched for: ${searchTerm}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
- Visiting http://localhost:3000/search?q=javascript sets
req.query.q
to “javascript”. - The server responds: You searched for: javascript.
- Multiple query parameters (e.g.,
/search?q=javascript&sort=asc
) are available asreq.query.q
andreq.query.sort
.
13. How do you set up CORS in Express?
CORS (Cross-Origin Resource Sharing) allows your Express server to accept requests from different domains (e.g., a frontend app hosted on a different server). The cors package simplifies enabling CORS in Express.
🔹 Steps:
- Install the cors package:
npm install cors
- Use the cors middleware in your app.
📦 Example:
const express = require("express");
const cors = require("cors");
const app = express();
const port = 3000;
// Enable CORS for all routes
app.use(cors());
app.get("/data", (req, res) => {
res.json({ message: "This data can be accessed from any domain!" });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
⚙️ How it works:
- The cors middleware adds headers to allow cross-origin requests.
- A frontend app on http://example.com can now fetch data from http://localhost:3000/data .
- You can customize CORS (e.g., allow specific domains) by passing options to
cors()
.
14. What is app.listen()
?
app.listen(port, [callback])
is an Express method that starts your server, making it listen for incoming HTTP requests on a specified port. The optional callback function runs when the server starts successfully.
Why is it important?
It’s the final step to make your app accessible to clients (e.g., browsers or API clients).
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Server is up!");
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
⚙️ How it works:
app.listen(3000, ...)
binds the server to port 3000.- The callback logs a message when the server starts.
- Visiting http://localhost:3000 shows: Server is up!.