2016-04-24 97 views
0

我使用angularjs與節點js作爲服務器。Angular JS Node JS錯誤的請求錯誤發佈

我通過這種方式從UI傳遞數據。

schatApp.controller('registerController', function($scope,$location,$http) { 

    $scope.RegisterCredentials=function(){   
    var data={ 
      "firstName":"simhachalamrsdafrds", 
      "lastName":"ajay", 
      "username":"asfsd", 
      "email":"[email protected]", 
      "provider":"local", 
      "displayName":"amruth" 
     }  

     // var json = "{\"firstName\": \"firstName\",\"lastName\": \"lastName\",\"username\": \"username\",\"email\": \"email\"}"; 

      var config = { 
       headers : { 
         contentType:'application/json; charset=utf-8', 
        dataType: 'json' 
       } 
      }  

     $http.post("/register",JSON.stringify(data),config).then(function sucess(result){ 
     // alert(JSON.stringify(result)); 
     },function failure(result){ 
     // alert(JSON.stringify(result)); 
     }); 
    } 
}); 

這是我的後端代碼

app.post('/register',function(req,res){  
    var data={ 
    firstName:'simhachalam', 
    lastName:'ajay', 
    username:'asfsdq', 
    email:'[email protected]', 
    provider:'local', 
    displayName:'amruth' 
    } 
console.log("111..............."); 
//console.log(req.body); 

//res.setHeader('Content-Type', 'application/json'); 
core.account.create('local',data,function(err){ 
if (err) { 
var message = 'Sorry, we could not process your request'; 
    if (err.code === 11000) { 
    message = 'Email has already been taken'; 
    } 
    return res.status(400).json({ 
       status: 'error', 
       message: message 
       }); 
    }  
    res.status(201).json({ 
        status: 'success', 
        message: 'You\'ve been registered, ' + 
          'please try logging in now!' 
        }); 
}); 

}); 

我得到400錯誤的請求。

+0

你應該檢查'err' –

+0

服務器端,你的'res.status(201)'在'return res.status(400)'之後,並且永遠不會被執行。如果(錯誤)'應該有'else'... – YvesLeBorg

回答

0

它很難說什麼可能是問題,你需要做一個console.log(err)對象。你能在這裏爲我們提供這些信息嗎?

if (err) { 
var message = 'Sorry, we could not process your request'; 
    if (err.code === 11000) { 
    message = 'Email has already been taken'; 
      } 
    return res.status(400).json({ 
      status: 'error', 
      message: message 
    }); 
} 

上面的代碼中明確指出,要返回res.status(400),你可以改變你的$ http.post以下和檢查。

$http({ 
    method: 'POST', 
    url: "/register", 
    data: JSON.stringify(data), 
    headers: {'Content-Type': 'application/json; charset=utf-8'} 
}); 

希望你/register endpoint託管你在哪裏服務客戶端在同一臺服務器上。