Express.js - express.json() 函式


express.json() 是 Express 中的內建中介軟體函式。該方法用於解析帶有 JSON 有效負載的傳入請求,並基於 bodyparser。

此方法返回僅解析 JSON 並且僅檢視內容型別標頭與 type 選項匹配的請求的中介功能。

語法

express.json([options])

引數

此方法有以下不同選項

  • options

    • inflate – 這會啟用或停用對鬆弛或壓縮體進行的處理。預設值:true

    • limit – 這會控制請求正文的最大大小。

    • reviver – 此選項以第二個引數傳遞給 JSON.parse 方法。

    • strict – 啟用或停用接受的陣列或物件。

    • type – 這決定要解析的中介功能的媒體型別。

示例 1

建立一個名為 "express.js" 的檔案,然後複製以下程式碼示例。建立檔案後,使用命令 **"node express.js"** 執行此程式碼。

// express.json() Demo Example

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

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

// Calling the express.json() method for parsing
app.use(express.json());

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

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

在命中 API 端點之前,設定以下兩個屬性

  • 在 Headers 中將 content-type 設定為 application/json

  • 在 POST 請求中傳遞以下 body – {"name": "TutorialsPoint"}

輸出

C:\home
ode>> node express.js Server listening on PORT 3000 tutorialspoint

示例 2

我們來看另一個示例。

// express.json() Demo Example

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

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

// Without using the json middleware

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

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

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

在命中 API 端點之前,設定以下兩個屬性

  • 在 Headers 中將 content-type 設定為 application/json

  • 在 POST 請求中傳遞以下 body – {"name": "TutorialsPoint"}

輸出

C:\home
ode>> node express.js Server listening on PORT 3000 TypeError: Cannot read property 'name' of undefined at /home/node/test/express.js:15:23 at Layer.handle [as handle_request] (/home/node/test/node_modules/express/lib/router/layer.js:95:5) at next (/home/node/test/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/home/node/test/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/node/test/node_modules/express/lib/router/layer.js:95:5)

更新於: 2021 年 10 月 1 日

15K+ 瀏覽

開始你的 職業生涯

完成課程,獲得認證

開始課程
廣告
© . All rights reserved.