简体   繁体   English

如何将User对象作为参数传递给node.js的Express api,例如asp.net

[英]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 . 我正在学习node.js,我需要将一个User对象传递给node.js的Express api,我看到的问题文档很少,但都涉及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. 但我需要知道bodyparser仅是解决此问题的好方法,否则我可以将.Net / Java做为User Type数据类型发送User对象。 i need to send the object exactly like given .net example. 我需要完全按照给定的.net示例发送对象。

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). 如果我通过ajax发送上述用户,则ASP.NET方法将自动适合我的asp.net方法的参数(用户u)。

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

Node.Js 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);
    });
});

Ok, using your above example. 好的,使用上面的示例。

Let's assume we have JSON post request -> 假设我们有JSON发布请求->

{
    "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. 无需使用所有锅炉代码来进行错误处理等,而是可以使用JS创建包装函数来处理此错误。 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. 对我来说,这看起来与ASP版本非常相似,并且实际上在做更多的事情,因为它实际上显示的是/save路由,而您没有在ASP版本中显示。

So the next stage is creating the handlePost function.. 因此,下一步是创建handlePost函数。

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 ,. 如果使用Promise,那么handlePost当然可以用于所有请求,实际上不仅是Post请求,因此我确实应该将其命名为handleReq or even ok like ASP did. 甚至ok像ASP一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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