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

更新於: 2021 年 10 月 1 日

782 次瀏覽

開啟您的職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.