2017-01-24 6 views
0

필자가 작성한 작은 노드 서버에 일부 데이터를 입력하려고합니다. 다음과 같이TypeError : null의 'save'속성을 읽을 수 없습니다.

서버 측의 코드는 다음과 같습니다

{ 
    "error": false, 
    "message": "Data is updated for nv942" 
} 

그러나, 데이터가 업데이트되지 않습니다

router.route('/returnLockID').put(function(req, res){ 
mongoOp.findOne({ 
    name: req.body.name 
}, function(err, user) { if(err) { 
    response = {"error" : true,"message" : "Error fetching data"}; 
} else { 
// we got data from Mongo. 
// change it accordingly. 
    if(req.body.LockID !== undefined) { 
     // case where ID needs to be updated. 
     user.LockID = req.body.LockID; 
    } 
    // save the data 
    user.save(function(err){ 
     if(err) { 
      response = {"error" : true,"message" : "Error updating data"}; 
     } else { 
      response = {"error" : false,"message" : "Data is updated for "+req.body.name}; 
     } 
     res.json(response); 
    }) 
} 
}); 
    }) 

내가 응답을 얻을. 누구나 내가 저축 한 곳을 볼 수 있습니까?

TypeError: Cannot read property 'save' of null 
    at /Users/NikhilVedi/Documents/FYP/Server/lockserver/routes/users.js:92:13 
    at Query.<anonymous> (/Users/NikhilVedi/Documents/FYP/Server/lockserver/node_modules/mongoose/lib/model.js:3407:16) 
    at /Users/NikhilVedi/Documents/FYP/Server/lockserver/node_modules/kareem/index.js:259:21 
    at /Users/NikhilVedi/Documents/FYP/Server/lockserver/node_modules/kareem/index.js:127:16 
    at _combinedTickCallback (internal/process/next_tick.js:67:7) 
    at process._tickCallback (internal/process/next_tick.js:98:9) 

스위프트 코드는 다음과 같습니다 :

@IBAction func setup(_ sender: Any) { 

     if (UserDefaults.standard.value(forKey: "userIP") == nil) 
     { 
      //make this a message box and stop the program crashing by assigning user defaults a value 
      UserDefaults.standard.set("localhost", forKey: "userIP") 

      print("Local host programatically set"); 
     } 

     let u = UserDefaults.standard.value(forKey: "userIP")! 
     let name = UserDefaults.standard.value(forKey: "email")! 
     var request = URLRequest(url: URL(string: "http://\(u):3000/users/returnLockID")!) 
     request.httpMethod = "PUT" 
     let postString = "LockID=\(LockID.text!)name=\(name)" 
     print(postString) 
     request.httpBody = postString.data(using: .utf8) 
     let task = URLSession.shared.dataTask(with: request) { data, response, error in 
      guard let data = data, error == nil else {             // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data, encoding: .utf8) 
      // print("responseString = \(responseString)") 

      if let data = responseString?.data(using: String.Encoding.utf8) { 
       let resString = JSON(data: data) 

       if resString["success"].stringValue == "true" 
       { 
        print("works"); 

       } 
       else if resString["success"].stringValue == "false" 
       { 
        print("failed") 
        print(resString["message"].stringValue) 
        //dismiss window and set bool to true 
        UserDefaults.standard.set(true, forKey: "LockIDPresent") 
        self.dismiss(animated: true, completion: nil); 
       } 

      } 

     } 
    task.resume() 
      } 

덕분에 내가 얻을 아이폰 OS에서 PUT 할 때 그것은 모두 내가 우체부를 사용하여 넣으면 잘 통과

, 난,하지만, 저장할 수 있습니다 미리!

답변

0

하나의 오류가 표시되지만 문제는 첫 번째 if 문절에 res.json(response);을 수행해야한다는 것입니다.

또 다른주의해야 할 점은 req.body.LockID 값이 제공되는지 여부에 관계없이 save을 호출한다는 것입니다. 따라서 사용자가 수정되지 않은 경우 사용자가 수정하지 않고 저장됩니다. 값이 req.body.LockID 인 경우 사용자 이메일이 업데이트되지 않을 수 있으므로 인쇄 해 두는 것이 좋습니다.

+0

그는 body.lockID = req.body.userEmail; body의 lockId가 아닌 전자 메일을 할당합니다. –

+0

예, 알았지 만, 그의 사업에 익숙하지 않아서 언급하지 않았습니다. 논리, 의도적 일 수 있습니다 ... 확실하지 않습니다. – GPicazo

+0

감사! 이제 Postman을 통해 PUT 및 저장을 완료 할 수 있지만 신속하게 오류가 발생합니다. 질문을 업데이트했습니다. – CS456

관련 문제