簡體   English   中英

以快遞方式解析從請求到類的正文

[英]Parsing Body from request to Class in express

我有疑問,我來自帶有 c# 的 .net,我想像 .net 那樣自動解析我的正文請求,如何將類或接口設置為 express 中的請求正文,我找到了很多選項,但所有他們中的一些只是將主體破壞為他們需要的屬性,我需要一種方法或方法來允許我只獲取我在我的類中指定的屬性。

在.Net 中會是這樣的。

  [HttpGet("someName")
Public IActionResult GetSomething(Myclass instance){
   // the instance with only the properties that i specified in my class and not the hole body with useless props that i don’t request

 instance.someProperty
 Return Ok()
}

ASP.net 實際上足夠聰明,可以理解當一個類被聲明為參數時,它必須從請求 POST 正文映射到該類。

Nodejs 和 express 並不總是附帶電池。

您需要添加一個可以讀取原始請求並獲取所需 json 對象的中間件。 如果您只接收 JSON,那么您需要 JSON 中間件。 如果您希望有 URL 編碼的帖子(用於文件上傳或 html s),那么您還需要添加 urlencoded 中間件

const app: Application = express();
(...)
app.use(express.json());
app.use(express.urlencoded());

此時,您可以聲明您的路線,express 將使用您的 post 數據正確填充 req.body 對象。

interface MyPostBody {
  foo: string;
  bar: string;
}

app.post("/api/someName", (req, res) => {
  const instance = req.body as MyPostBody;
  console.log(instance.foo);
  console.log(instance.bar);
  const result = doSomething(instance);
  res.send(result);
});

請注意,我們只是在這里轉換類型,所以如果您的客戶端發送一個不符合 MyPostBody 接口的對象,事情就會中斷。 您可能需要添加一些驗證以確保數據符合您的 api 合同。 您可以為此使用一些驗證,例如是的。 為了簡單起見,我將在這里做一些非常基本的事情。

app.post("/api/someName", (req, res) => {
  if(req.body.foo === null || req.body.foo === undefined) {
    res.status(400).send("foo is required");
    return;
  }
  if(req.body.bar === null || req.body.bar === undefined) {
    res.status(400).send("bar is required");
    return;
  }

  const instance = req.body as MyPostBody;
  console.log(instance.foo);
  console.log(instance.bar);
  const result = doSomething(instance);
  res.send(result);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM