Handling http requests with Express
This tutorial will helps you to learn how to handle the http requests in Express.
Introduction to Handling HTTP Requests with Express
- Express is a web application framework for Node.js that simplifies the process of handling HTTP requests and responses.
- In this tutorial, we'll cover how to handle GET and POST requests, work with URL parameters and query parameters, deal with request headers, and send responses.
Setting Up Express and Creating a Basic Server
- First, create a new Node.js project and install the Express package.
npm init
npm install express
Create a basic Express server as described in the previous tutorials.
Handling GET Requests
- Use the .get() method to handle GET requests.
app.get('/home', (req, res) => {
res.send('Welcome to the home page!');
});
Handling POST Requests
- Use the .post() method to handle POST requests.
app.post('/submit', (req, res) => {
const data = req.body;
res.send(`Received: ${data.username}, ${data.email}`);
});
Handling URL Parameters
- Define URL parameters using a colon in the route path.
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
Handling Query Parameters
- Access query parameters using req.query.
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`Search Query: ${query}`);
});
Handling Request Headers
- Access request headers using req.headers.
Sending Responses
- Use res.send(), res.json(), or other methods to send responses.
app.get('/json', (req, res) => {
const data = { message: 'Hello, JSON!' };
res.json(data);
});
Error Handling
- Handle errors using next(err) in route handlers.
app.get('/error', (req, res, next) => {
const error = new Error('This is an error');
next(error);
});
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send('Internal Server Error');
});