Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Express.js – express.text() function
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
ode>> 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
ode>> node expressText.js Server listening on PORT 3000 undefined