![](/img/trans.png)
[英]NodeJS express/request: piping a POST request with body parsing issue
[英]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.