Express.js is a fast, minimal, and flexible web application framework for Node.js. It simplifies the process of building web applications and APIs by providing a robust set of features for routing, middleware, and handling HTTP requests and responses.
Key Features of Express.js:
✅ Routing – Define URL endpoints and handle requests efficiently.
✅ Middleware – Process requests before reaching the final handler (e.g., authentication, logging).
✅ Template Engines – Render dynamic HTML using engines like EJS or Handlebars.
✅ REST API Support – Easily build APIs with methods like GET, POST, PUT, and DELETE.
✅ Integration with Databases – Works well with MongoDB (Mongoose), MySQL, and others.
Write a 'Hello World' ExpressJS application.
// Import the express module
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
const PORT = 3000;
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Mentions few features of ExpressJS.
Few features of the ExpressJS includes
- Routing: Express provides a simple way to define routes for handling HTTP requests. Routes are used to map different URLs to specific pieces of code, making it easy to organize your application's logic.
- Middleware: Express uses middleware functions to perform tasks during the request-response cycle. Middleware functions have access to the request, response, and the next middleware function.
- HTTP Utility Methods: Express mainly used for handling HTTP methods like GET, POST, PUT, and DELETE. This makes it easy to define how the application should respond to different types of HTTP requests.
- Static File Serving: It can also serve static files, such as images, CSS, and JavaScript, with the help of built-in express.static middleware.
- Security: It includes features and middleware to strengthen the security of your web applications, such as the helmet middleware to secure your app.
Create a simple middleware for validating user.
// Simple user validation middleware
const validateUser = (req, res, next) => {
const user = req.user;
if (!user) {
return res.status(401).json({ error: 'Unauthorized - User not found' });
}
next();
};
app.get('/profile', validateUser, (req, res) => {
const user = req.user;
res.json({ message: 'Profile page', username: user.username });
});
How would you render plain HTML using ExpressJS?
In ExpressJS, you can render plain HTML using the res.send() method or res.sendFile() method.
Sample code:
JavaScript
JavaScript
//using res.send
const express = require('express');
const app = express();
const port = 8000;
app.get('/', (req, res) => {
const htmlContent = '<html><body><h1>Hello, World!</h1></body></html>';
res.send(htmlContent);
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
