Express.js – express.urlencoded() 方法
**express.urlencoded()** 是 Express.js 中內建的中介軟體。此方法的主要目的是解析帶有 **urlencoded** 負載的傳入請求,並且基於 body-parser。
此方法返回解析所有 **urlencoded** 主體的中介軟體。
語法
express.urlencoded( [options] )
引數
以下是此方法可用的不同選項:
**options** −
**inflate** − 啟用或停用對已解壓縮或壓縮主體的處理。預設值:true
**limit** − 控制請求主體的最大大小。
**extended** − 此選項允許在使用 queryString 庫或 qs 庫解析 URL 編碼資料之間進行選擇。
**type** − 確定將被解析的中介軟體的媒體型別。
**parameterLimit** − 此選項控制 URL 編碼資料中允許的最大引數數量。
示例 1
建立一個名為“**urlencoded.js**”的檔案並複製以下程式碼片段。建立檔案後,使用命令“**node urlencoded.js**”執行此程式碼,如下例所示:
// express.urlencoded() 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 read encoded 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 設定為 **application/x-www-form-urlencoded**。
在 POST 請求中傳遞以下主體:**{"name": "TutorialsPoint"}**
輸出
C:\home
ode>> node urlencoded.js Server listening on PORT 3000 [Object: null prototype] { '{
"title": "tutorialspoint"
}': '' }
示例 2
讓我們來看另一個例子。
// express.urlencoded() 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.urlencoded middleware
// app.use(express.urlencoded({extended:false}));
// 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 設定為 **application/x-www-form-urlencoded**。
在 **POST** 請求中傳遞以下主體:**{"name": "TutorialsPoint"}**
輸出
C:\home
ode>> node urlencoded.js Server listening on PORT 3000 undefined
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP