request data in express

Request Data in Express

If you want to extract data from a request in Express, you can do so by accessing the req.body property. To use this property, you need to install and use the body-parser middleware.

Installing Body-Parser

To install body-parser, run the following command:


      npm install body-parser --save
    

Using Body-Parser

To use body-parser, require it in your server file and add it as middleware before your routes:


      const express = require('express');
      const bodyParser = require('body-parser');
      const app = express();

      app.use(bodyParser.urlencoded({ extended: false }));
      app.use(bodyParser.json());

      // Your routes here
    

The urlencoded middleware parses incoming requests with urlencoded payloads and is based on querystring library. The extended option allows to choose between parsing the URL-encoded data with the qs library (when set to false) or the native querystring library (when set to true). The default value is true.

The json middleware parses incoming requests with JSON payloads.

Accessing Request Data

After you have installed and used body-parser, you can access request data from req.body. For example:


      app.post('/submit-form', (req, res) => {
        console.log(req.body);
        res.send('Received data');
      });
    

In the above code snippet, we have defined a route that listens for a POST request to /submit-form. When a request is made to this route, we log the request data to the console and send a response to the client.

You can also use the req.query object to access query parameters from the URL:


      app.get('/search', (req, res) => {
        console.log(req.query);
        res.send('Received search query');
      });
    

In the above code snippet, we have defined a route that listens for a GET request to /search. When a request is made to this route, we log the query parameters to the console and send a response to the client.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe