Express.js – express.text() function

Express JSServer Side ProgrammingProgramming

express.text() is a built-in middleware function in Express. It parses the incoming request payloads into a string and it is based upon the body-parser. This method returns the middleware that parses all the bodies as strings.

Syntax

express.text([options])

Parameters

Following are the different options available with this method

  • options

    • inflate – It enables or disables the handling of the deflated or compressed bodies. Default: true

    • limit – It controls the maximum size of the request body.

    • defaultCharset – This option specifies the default character set for the text content if the charset is not specified in the Content-type header of the request.

    • type – It determines the media type for the middleware that will be parsed.

Example 1

Create a file with the name "expressText.js" and copy the following code snippet. After creating the file, use the command "node expressText.js" to run this code.

// express.text() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Using the express.text middleware

// to convert into string
app.use(express.text());

// Reading content-type
app.post('/', function (req, res) {
   console.log(req.body)
   res.end();
})

// Listening to the port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Before hitting the API endpoint, set the following two properties −

  • Set the content-type as text/plain in headers.

  • Pass the following body in the POST request – {"name": "TutorialsPoint"}

Output

C:\home\node>> node expressText.js
Server listening on PORT 3000
{
   "title": "tutorialspoint"
}

Example 2

Let’s take a look at one more example.

// express.text() Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Commenting the express.text middleware

// to convert into string

// app.use(express.text());

// Reading content-type
app.post('/', function (req, res) {
   console.log(req.body)
   res.end();
})

// Listening to the port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Before hitting the API endpoint, set the following two properties −

  • Set the content-type as text/plain in headers.

  • Pass the following body in the POST request – {"name": "TutorialsPoint"}

Output

C:\home\node>> node expressText.js
Server listening on PORT 3000
undefined
raja
Published on 01-Oct-2021 06:41:11
Advertisements