Express.js – express.text() 函式
express.text() 是 Express 中的內建中介軟體函式。它將傳入請求負載解析為字串,且基於 body-parser。此方法返回將所有主體解析為字串的中介軟體。
語法
express.text([options])
引數
以下是此方法可用的不同選項
options
inflate – 啟用或停用對已放氣或壓縮的主體的處理。預設: true
limit – 控制請求主體的最大大小。
defaultCharset – 如果沒有在請求的 Content-type 標頭中指定字元集,則此選項將指定文字內容的預設字元集。
type – 確定將解析中介軟體的媒體型別。
示例 1
建立一個名為 "expressText.js" 的檔案,複製以下程式碼段。建立檔案後,使用命令 "node expressText.js" 執行此程式碼。
// 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);
});在命中 API 終結點之前,設定以下兩個屬性 −
在標頭中將 content-type 設定為 text/plain。
在 POST 請求中傳遞以下主體 – {"name": "TutorialsPoint"}
輸出
C:\home
ode>> node expressText.js Server listening on PORT 3000 { "title": "tutorialspoint" }
示例 2
我們來看另一個示例。
// 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);
});在命中 API 終結點之前,設定以下兩個屬性 −
在標頭中將 content-type 設定為 text/plain。
在 POST 請求中傳遞以下主體 – {"name": "TutorialsPoint"}
輸出
C:\home
ode>> node expressText.js Server listening on PORT 3000 undefined
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP