2017-02-13 29 views
1

我正在創建一個RESTful API。爲什麼不能將Restful傳遞到數據庫中

我想用GET方法檢查lastName是否存在。如果可以找到姓氏,則返回「YES」,否則,調用POST方法創建輸入lastName的數據。

問題是它可以創建一個新的數據,但是主體是空的。理想情況下,它應該包含與lastName的值,如"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方法效果很好,不是問題。

+0

你是不是使用後的路線在同一臺服務器?該xmlhttprequest發臭,它不應該在這裏,而是使用'request'或類似的。你爲什麼這樣做:第一個地方?只需在dba本地創建用戶即可。 – Zlatko

+0

@Zlatko感謝您的評論。我剛開始學習RESTful API,不太好。我想先檢查姓氏是否存在,如果沒有找到,則創建爲dba。你能給我提供一個如何使用'request'的例子嗎?謝謝 – Wei

+0

有多條路線。查看MongoDB的upsert(更新現有的文檔,或創建一個新的文檔,如果它不存在)。但是,如果這不起作用,您就已經在這裏建立起來,您沒有用戶 - 所以馬上創建一個。 – Zlatko

回答

1

讓我修改了一下你的代碼,並添加註釋爲指針:

// 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 
     }); 
     }); 
    }); 
    }) 
+0

非常感謝你提供這樣一個很好的例子,Zlatko! – Wei

相關問題