The goal of this tutorial is to teach you how to handle HTTP requests and responses using Express, a flexible Node.js web application framework. By the end of this tutorial, you will learn how to extract information from requests, send different types of responses, and understand the basics of how data is transferred between client and server.
For this tutorial, you should have a basic understanding of:
- JavaScript, as Express is a Node.js framework
- Node.js and npm (Node Package Manager)
- HTTP (Hypertext Transfer Protocol)
Every interaction between a client (usually a web browser) and a server involves sending a request and receiving a response. In Express, these are represented by the Request (req
) and Response (res
) objects.
A HTTP request contains all the information a server needs to understand and respond to it. This includes the request method (GET, POST, etc.), the URL, headers, and any data sent by the client.
A HTTP response is what the server sends back to the client. It includes a status code, headers, and any data the server wants to send back.
In Express, you handle requests with middleware functions, which have access to the req
and res
objects and a next
function. You define these functions and then tell Express to use them.
Here's a basic example of an Express server that responds to GET requests at the root URL (/
).
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
app.get
tells Express to use the provided function for all GET requests to the /
URL.(req, res) => {}
is the function that handles these requests.res.send
sends a response back to the client.When you run this server and visit http://localhost:3000
in your browser, you should see "Hello, world!".
In this tutorial, you've learned how to handle HTTP requests and responses in Express, how to extract information from requests, and how to send responses. You've also seen how to define middleware functions and use them in Express.
To learn more about Express and its features, check out the official Express.js documentation.
/data
URL, and responds with the same data it receives.const express = require('express');
const app = express();
app.use(express.json()); // for parsing application/json
app.post('/data', (req, res) => {
res.json(req.body);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
app.post('/data', (req, res) => {
res.status(418).json(req.body);
});
res.status(418)
sets the status code of the response to 418. You can use any valid HTTP status code here.