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:
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.
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.
// 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!');
});
// 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');
});
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' }
.
// 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' }
.
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.
name
query parameter.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!');
});