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

  1. Express is a web application framework for Node.js that simplifies the process of handling HTTP requests and responses.
  2. 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

  1. 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

  1. Use the .get() method to handle GET requests.
app.get('/home', (req, res) => {
    res.send('Welcome to the home page!');
});
  

Handling POST Requests

  1. 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

  1. 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

  1. Access query parameters using req.query.
app.get('/search', (req, res) => {
    const query = req.query.q;
    res.send(`Search Query: ${query}`);
});
  

Handling Request Headers

  1. Access request headers using req.headers.

Sending Responses

  1. 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

  1. 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');
});