sebu
sebu

Reputation: 2954

How to Pass a User object as parameter to node.js's Express api like asp.net

I am learning node.js, i need to pass a User object to node.js's Express api, i have seen few documents for my question, but its all about bodyparser. but i need to know is bodyparser only the good solution for this problem, or i can send the User object as Object Type Data Type which .Net/Java do. i need to send the object exactly like given .net example.

User Object

var user={
    "Id":1,
    "FullName":"Mr. X"
}

ASP.NET Method if i send the above user via ajax its automatically fit with my asp.net method's parameter(User u).

public IHttpActionResult Save(User u)
{
    return Ok(_userService.Save(u));
}

Node.Js

var req=require('body-parser');
router.post('/save', function (req, res) {
    var user=req.body.User;
    return userServices.Save(user).then(function (results) {
        res.send(results);
    }).catch(function (reason) {
        res.send(reason);
    });
});

Upvotes: 0

Views: 651

Answers (1)

Keith
Keith

Reputation: 24231

Ok, using your above example.

Let's assume we have JSON post request ->

{
    "Id":1,
    "FullName":"Mr. X"
}

Instead of having all the boiler code for error handling etc, with JS you can create a wrapper function to handle this. Seen as your using promises this is even better.

So what were after is something like ->

router.post('/save', handlePost((user) => userServices.Save(user)) );

To me, that looks pretty much similiar to the ASP version, and in fact is doing more as it's actually showing the route /save, that you didn't show in the ASP version.

So the next stage is creating the handlePost function..

function handlePost(func) {
  return (req, res) => {
    func(req.body).then((results) => {
      res.send(results);
    }).catch((reason) => {
      res.status(500).send(reason);
    });    
  }
}

Hopefully this is what you was after.

The handlePost, of course can be re-used for all your requests if using promises, in fact not just Post requests, so I really should have named it handleReq,. or even ok like ASP did.

Upvotes: 1

Related Questions