简体   繁体   中英

Parsing Body from request to Class in express

I got doubt, im coming from .net with c# and i want to parse my body request as .net does for my automatically, how can i set a class or an interface as a request body in express, i have found many options but all of them just destruct the body into the properties that they need, i need a way or a method that allows me to get only the properties that i specified in my class.

In .Net it will be something like this.

  [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 is actually smart enough to understand that when a class is declared as an argument, it must map from the request POST body to the class.

Nodejs and express do not always come with batteries included.

You need to add a middleware that can read the raw request and get the json object you want. If you are only receiving JSON then you need the JSON middleware. If you expect to have URL encoded posts (for file uploading or html s) then you also need to add the urlencoded middleware

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

At this point, you can declare your route, and express will corectly fill the req.body object with your post data.

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

Please be aware that we are just casting the type here, so if your client sends an object that does not conform to the MyPostBody interface, things will break. You probably need to add some validation to ensure the data conforms to you api contract. You can use some validation library like yup for that. To keep it simple I will do something very basic here.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM