正在将正文从请求解析为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),那么你还需要添加URL编码的中间件

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合约。你可以使用一些验证库,比如yup。为了简单起见,我将在这里做一些非常基本的事情。

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);
});

最新更新