Express.js / Express.js Basics
Handling Requests and Responses
This tutorial focuses on handling requests and responses in Express.js. You will learn how to retrieve information from requests and how to send responses back to the client.
Section overview
5 resourcesCovers the fundamental concepts of Express.js, including installation, setup, and creating a basic application.
Handling Requests and Responses in Express.js
1. Introduction
This tutorial will guide you through the process of handling HTTP requests and responses using Express.js, a popular Node.js web application framework. You will learn how to extract information from requests, how to construct and send responses back to the client, and best practices for managing these tasks.
By the end of this tutorial, you'll be able to:
- Retrieve data from GET and POST requests
- Send responses with various HTTP status codes
- Handle errors in your Express.js application
Prerequisites: Basic understanding of JavaScript and familiarity with Node.js and Express.js. If you're new to these, you might want to check out some introductory tutorials first.
2. Step-by-Step Guide
Express.js provides a simple API for handling requests and responses. The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Example: Handling GET Requests
// This is a route handler for GET requests to the / route
app.get('/', (req, res) => {
// Send a response back to the client
res.send('Hello, World!');
});
Example: Handling POST Requests
// This is a route handler for POST requests to the / route
app.post('/', (req, res) => {
// Send a response back to the client
res.send('You made a POST request');
});
3. Code Examples
Example 1: Extract Query Parameters from GET Requests
app.get('/search', (req, res) => {
// req.query contains the query parameters
console.log(req.query);
res.send(`You searched for ${req.query.q}`);
});
When you visit http://localhost:3000/search?q=express, the app responds with "You searched for express", and console.log(req.query) outputs { q: 'express' }.
Example 2: Extract Data from POST Requests
// In order to parse incoming requests with JSON payloads, we use express.json() middleware
app.use(express.json());
app.post('/login', (req, res) => {
// req.body contains the body of the request
console.log(req.body);
res.send(`Welcome, ${req.body.username}`);
});
If you make a POST request to http://localhost:3000/login with { "username": "John" } as the body, the app responds with "Welcome, John", and console.log(req.body) outputs { username: 'John' }.
4. Summary
In this tutorial, we've covered how to handle GET and POST requests in Express.js, how to extract data from these requests, and how to send responses back to the client. As a next step, you could explore handling PUT and DELETE requests, or look at using middleware for tasks such as error handling and logging.
5. Practice Exercises
- Create an Express app that responds with "Hello, [name]" when a GET request is made to the "/greet" route with a
namequery parameter. - Create an Express app that accepts POST requests at the "/data" route, logs the request body to the console, and responds with a status code of 200.
- Create an Express app that responds with a custom error message and a status code of 404 when a GET request is made to an undefined route.
Solutions:
app.get('/greet', (req, res) => {
res.send(`Hello, ${req.query.name}`);
});
app.post('/data', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
app.use((req, res) => {
res.status(404).send('Sorry, we could not find that!');
});
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article