【问题标题】:Why can't Restful pass body into database为什么Restful不能将正文传递到数据库
【发布时间】:2017-07-02 01:20:39
【问题描述】:

我正在创建一个 RESTful API。

我想使用 GET 方法来检查 lastName 是否存在。如果能找到lastName,返回“YES”,否则调用POST方法创建一个输入lastName的数据。

问题是它可以创建一个新数据,但是body是空的。理想情况下,它应该包含一个带有姓氏的值,例如"lastName": "James",

{
  "_id": "58a22c3c3f07b1fc455333a5",
  "__v": 0
}

这是我的代码。

router.route("/findLastName/:id")
    .get(function(req,res){
        var response;
        mongoOp.findOne({deviceID: req.params.id}, function(err, result){
          if (err) { 
            response = {"error" : true,"message" : "Error fetching data"};
            res.json(response);
          }
          if (result) {
            response = "YES";
            res.send(response);
          } else {
            var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
            var xhr = new XMLHttpRequest();
            var POSTurl = "http://localhost:6002/users";
            var params = "lastName=" + req.params.id;

            xhr.open("POST", POSTurl, true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(params);
          }
        });
      })

PS:GET 方法效果很好,不是问题。

【问题讨论】:

  • 您不是在使用同一台服务器进行发布路由吗?那个 xmlhttprequest 很臭,它不应该在这里,使用request 或类似的代替。你为什么这样做:第一?只需立即在 dba 中本地创建用户。
  • @Zlatko 感谢您的评论。我刚开始学习RESTful API,不太好。我想首先检查 lastName 是否存在,如果找不到,则创建到 dba 中。你能给我一个如何使用request的例子吗?谢谢
  • 有多条路线。查看 MongoDB upsert(更新现有文档,如果不存在则创建一个新文档)。但如果这不起作用,您已经在这里确定您没有用户 - 所以立即创建一个。

标签: node.js rest api xmlhttprequest


【解决方案1】:

让我修改一下你的代码并添加 cmets 作为指针:

// changed findLastName to find-last-name. It's a common convention,
// urls need to be case insensitive. It doesn't concern lastName, as
// that's a parameter, internal to your app so it's fine.
// even better if you name the route `find-or-create` or something, to better
// reflect what you're doing.
router.route("/find-last-name/:lastName")
.get(function(req,res){
    var response;
    mongoOp.findOne({deviceID: req.params.lastName}, function(err, result){
      if (err) { 
        response = {"error" : true,"message" : "Error fetching data"};
        // Adding a `return statement here. If you don't return, you'll tell 
        // the user that there was an error, but your code continues running
        // potentially calling that res.json twice.
        // Also, since it's an internal error, it's common to tell the client
        // about it, by setting the status to 500
        return res.status(500).json(response);
      }
      if (result) {
        // turning the message to JSON instead. You started that above,
        // and for the sake of your clients (your frontend), it's 
        // better to stick to JSON. Also you can pass useful info, such as
        // _id of the document.

        // Again adding a `return` here, and then the rest of the code
        // is nested one level less. not required, but some people like that.
        response = {
          message: "Last name exists."
        };
        return res.json(response);
      }
      // Here begins the new code. I'm typing what I can infer from your code,
      // I don't know if your MongoDB driver looks like that exactly.
      mongoOp.insert({ 
        deviceId: req.params.lastName
        // add other optional properties here.
      }, function (err, response) {
        if (err) {
          var message = {
            error: true,
            message: 'Cannot save new entry.'
          }
          return res.status(500).json(message);
        }
        // if we're here, everything went ok. You can probably return
        // the _id of the given user.
        return res.json({
          message: 'New user created.',
          _id: response._id
        });
      });
    });
  })

【讨论】:

  • 非常感谢你提供了这么好的例子,Zlatko!
猜你喜欢
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2012-07-05
  • 2015-04-27
  • 2017-07-20
  • 2020-02-09
相关资源
最近更新 更多