在我的快遞應用程式中,我想檢查正文長度并限制它,而不管內容型別如何。在此之后,如果內容型別為 json,我想決議正文。我怎樣才能做到這一點?目前我的代碼如下所示,但服務器在 express.json() 中間件處停止:
const express = require('express')
const contentType = require('content-type')
const getRawBody = require('raw-body')
const app = express()
app.use(function(req, res, next) {
const cType = req.headers['content-type'] || ''
getRawBody(req, {
length: req.headers['content-length'],
limit: '1mb',
encoding: contentType.parse(cType).parameters.charset
}, function(err, string) {
if(err) {
next(err)
}
next()
})
})
app.use(express.json())
uj5u.com熱心網友回復:
你不能那樣實施。 express.json()期望從傳入的流中讀取正文內容。但是,raw-body已經從流中讀取了正文內容,因此當express.json()嘗試讀取它時,它會卡住等待讀取的內容。
由于express.json()做了兩件事,從流中讀取主體,然后將其決議為 JSON,因此用您自己的版本替換這兩件事應該很容易。第一個已經完成(讀取正文),所以您所要做的就是呼叫JSON.parse()您已經閱讀的原始正文內容,如果(且僅當)內容型別為"application/json". 洗掉對 的呼叫express.json():
app.use(function(req, res, next) {
const cType = req.headers['content-type'] || ''
getRawBody(req, {
length: req.headers['content-length'],
limit: '1mb',
encoding: contentType.parse(cType).parameters.charset
}, function(err, string) {
if(err) {
next(err)
} else {
if (req.get('Content-Type').toLowerCase() === "application/json") {
try {
// try parsing the body as JSON
req.body = JSON.parse(req.body);
next();
} catch(e) {
console.log(e);
next(e);
}
} else {
// not JSON, will leave the raw body in req.body
next();
}
}
})
})
請注意,如果您的應用程式需要任何其他內容型別(如表單資料),您還必須手動決議它們,因為這些其他型別的標準 express 中間件也會有同樣的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/359511.html
標籤:javascript 节点.js json 表达
