Skip to content
the poor coder

request data in express

Poor Man
Published
Reading time
1 min read
On this page

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:

Shell

      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:

JavaScript

      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:

JavaScript

      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:

JavaScript

      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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC