1. What is express.static()?
express.static() is a built-in Express middleware that serves static files (like HTML, CSS, images, or JavaScript) from a specified folder. When a client requests a file, Express automatically sends it without needing a custom route.
Why use it?
- Simplifies serving assets like stylesheets, scripts, or images for your web app.
- No need to write routes for each file.
📦 Example:
- Create a folder named
publicin your project with anindex.htmlfile:
<!-- public/index.html -->
<h1>Welcome to my site!</h1>- Set up your Express app:
const express = require("express");
const app = express();
const port = 3000;
// Serve static files from the 'public' folder
app.use(express.static("public"));
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
- Visiting http://localhost:3000/index.html serves the
index.htmlfile from thepublicfolder. - If you add
public/styles.css, it’s available at http://localhost:3000/styles.css . - The
publicfolder acts like the root directory for static files.
2. How do you handle errors in Express?
Express allows you to handle errors using special error-handling middleware. This middleware has four parameters (err, req, res, next) and is called when an error occurs in your app. You can use it to send custom error messages or log errors.
🔹 Steps:
- Define error-handling middleware at the end of your middleware stack.
- Use
next(err)in routes to pass errors to this middleware. - Send a response with an error message and status code.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res, next) => {
try {
throw new Error("Something went wrong!");
} catch (err) {
next(err); // Pass error to error-handling middleware
}
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.message); // Log the error
res.status(500).send("Oops, something broke!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
The / route throws an error, which is passed to the error-handling middleware via next(err).
The middleware catches the error, logs it, and sends a 500 status with a message.
Visiting http://localhost:3000 shows: Oops, something broke!.
3. What is the difference between app.get() and app.use()?
In Express, app.get() and app.use() serve different purposes:
app.get(path, callback)
Defines a route handler for GET requests to a specific URL path. It’s used to send responses for specific routes and HTTP methods.
app.use([path], callback)
Applies middleware or route handlers to all HTTP methods (GET, POST, etc.) for a given path (or all paths if no path is specified). It’s commonly used for middleware.
Key Differences:
app.get()is specific to GET requests;app.use()applies to all HTTP methods.app.get()is typically used for routes;app.use()is used for middleware or general-purpose handlers.app.use()can take an optional path, whileapp.get()always requires a path.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
// Middleware with app.use
app.use((req, res, next) => {
console.log("This runs for ALL requests");
next();
});
// Route with app.get
app.get("/home", (req, res) => {
res.send("Welcome to the home page!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
- The
app.usemiddleware logs a message for all requests, regardless of the URL or method. - The
app.getroute only responds to GET requests to /home. - Visiting http://localhost:3000/home logs the middleware message and shows:
Welcome to the home page!.
4. How do you serve HTML files in Express?
To serve HTML files in Express, you use res.sendFile() to send a specific file to the client. The path module is often used to create absolute file paths to avoid errors across different operating systems.
🔹 Steps:
- Create an HTML file in your project (e.g.,
public/index.html). - Use
res.sendFile()with the absolute path to the file. - Optionally, use
express.static()to serve the entire folder containing the HTML file.
📦 Example:
- Create public/index.html:
<h1>My Express Website</h1>
<p>Welcome to my page!</p>- Set up your Express app: javascript
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.sendFile(path.join(\_\_dirname, 'public', 'index.html'));
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
path.join(\_\_dirname, 'public', 'index.html')creates the absolute path to index.html.- Visiting http://localhost:3000 displays the HTML
- content: My Express Website and Welcome to my page!.
5. What is the purpose of next() in middleware?
In Express middleware, next() is a function that passes control to the next middleware or route handler in the chain. If you don’t call next(), the request will hang, and the client won’t receive a response.
Why is it needed?
Middleware often performs tasks (e.g., logging, authentication) and then hands off the request to the next handler.
next() ensures the request continues processing.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
// Middleware 1
app.use((req, res, next) => {
console.log("Middleware 1: Logging request");
next(); // Move to the next middleware
});
// Middleware 2
app.use((req, res, next) => {
console.log("Middleware 2: Adding timestamp");
req.timestamp = new Date();
next(); // Move to the route
});
// Route
app.get("/", (req, res) => {
res.send(`Request processed at: ${req.timestamp}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
- Middleware 1 logs a message and calls
next()to pass control. - Middleware 2 adds a timestamp to req and calls
next(). - The route uses the timestamp and sends a response.
- Visiting http://localhost:3000 shows something like:
Request processed at: 2025-07-28T16:34:00.000Z.
6. How do you handle 404 errors in Express?
A 404 error occurs when a client requests a route that doesn’t exist. In Express, you handle 404 errors by adding a middleware function at the end of your middleware and route stack. This middleware catches any unmatched requests and sends a 404 response.
🔹 Steps:
- Place the 404 middleware after all routes.
- Use
res.status(404)to set the HTTP status and send a response.
📦 Example:
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Home page");
});
// 404 middleware (must be last)
app.use((req, res) => {
res.status(404).send("Page not found!");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
- Visiting http://localhost:3000/ shows: Home page.
- Visiting http://localhost:3000/random (an undefined route) shows: Page not found! with a 404 status code.
7. What is Express Router?
Express Router is a feature in Express.js that lets you group related routes and middleware into a separate, reusable module. It’s like a mini Express app that handles specific routes, making your code more organized and easier to maintain, especially for large apps.
Why use it?
- Keeps your main app.js file clean by moving routes to separate files.
- Makes routes reusable across different parts of your app.
- Simplifies managing related routes (e.g., all user-related routes in one place).
📦 Example:
- Create a file named userRoutes.js:
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send("List of users");
});
router.get("/:id", (req, res) => {
res.send(`User with ID: ${req.params.id}`);
});
module.exports = router;- Use it in app.js:
const express = require("express");
const app = express();
const port = 3000;
const userRoutes = require("./userRoutes");
app.use("/users", userRoutes);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
express.Router()creates a router instance.- Routes defined in userRoutes.js handle requests to /users (e.g., http://localhost:3000/users shows “List of users”).
- /users/:id handles requests like http://localhost:3000/users/123 , showing “User with ID: 123”.
8. How do you use Express Router?
Using Express Router involves creating a router instance, defining routes on it, and then mounting it on your Express app with app.use(). This lets you organize routes into separate files and attach them to specific paths.
🔹 Steps:
- Create a router in a separate file (e.g., routes/users.js).
- Define routes using
router.get(),router.post(), etc. Export the router and use it in your main app withapp.use().
📦 Example:
- Create routes/users.js:
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send("All users");
});
router.get("/profile", (req, res) => {
res.send("User profile page");
});
module.exports = router;- Use it in app.js:
const express = require("express");
const app = express();
const port = 3000;
const userRoutes = require("./routes/users");
app.use("/users", userRoutes);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});⚙️ How it works:
- Visiting http://localhost:3000/users shows “All users”.
- Visiting http://localhost:3000/users/profile shows “User profile page”.
app.use('/users', userRoutes)mounts the router so all its routes start with /users.