1. Working with Express.js
Express.js is a popular web application framework for Node.js, designed to simplify the process of building robust web applications and APIs. It provides a lightweight and flexible environment to manage web servers, handle routing, and implement middleware.
2. What is Express.js?
Express.js is a minimal and fast web framework built on top of Node.js. It streamlines the development process by providing essential features such as:
1. Routing: Managing different URLs and HTTP methods.
2. Middleware Support: Enhancing request/response handling.
3. Template Engine Integration: Rendering dynamic content.
4. Error Handling: Catching and managing errors efficiently.
3. Why Use Express.js?
1. Simple and Minimalistic: Easy to set up and use with minimal boilerplate.
2. Extensive Middleware Support: A vast ecosystem of third-party middleware for added functionality.
3. Flexibility: Works with databases, templating engines, and authentication systems.
4. Scalability: Suitable for both small projects and large enterprise-level applications.
4. Routing in Express.js
Express.js provides a simple yet powerful way to handle routing. Each route is associated with an HTTP method like GET, POST, PUT, or DELETE.
Example: Defining Routes
app.get('/about', (req, res) => {
res.send('About Us');
});
app.post('/submit', (req, res) => {
res.send('Form submitted!');
});
Explanation:
5. Using Middleware in Express.js
Middleware functions are essential in Express.js for processing requests before they reach the final route handler.
Example: Logging Middleware
app.use((req, res, next) => {
console.log(`Request Method: ${req.method}, URL: ${req.url}`);
next();
});
6. Serving Static Files
Express can serve static files like HTML, CSS, and JavaScript using the express.static middleware.
Example: Serving Static Files
app.use(express.static('public'));
Place your static files (e.g., index.html, style.css) in a folder named public.
7. Handling Form Data
To handle form submissions, Express provides built-in middleware to parse incoming data.
Example: Handling JSON Data
app.use(express.json());
app.post('/data', (req, res) => {
console.log(req.body);
res.send('Data received!');
});
8. Error Handling in Express.js
Express has a built-in mechanism for error handling. You can define an error-handling middleware function.
Example: Custom Error Handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
9. Building a Simple API with Express.js
Let’s create a simple API that returns a list of users.
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
app.get('/api/users', (req, res) => {
res.json(users);
});