Angular + Express 指示空数据库结果集的标准方法是什么?



将空数据对象返回给我的 Angular 控制器并在那里询问它是指示"未找到用户"的正确方法,如下所示? 似乎猫鼬或我自己的 API 至少应该返回 {},然后我可以询问一些具体的东西,比如 data.username。

我当然可以做到这一点,但什么是标准?

(Express code)
-------------------------------------------------------------------------------------
app.get('/api/memberconfirm/:code', function (req, res) {
    return db.userModel.findOne({'confirmcode': req.params.code}, function (err, data) {
         if (!err) {
              return res.send(data);
         }
         else {
              console.log("error");
              return something...
         }
    });
});

(Angular code)
-------------------------------------------------------------------------------------------
controllerModule.controller('MemberConfirm', ['$scope', '$http', '$routeParams', '$location',
      function MemberConfirm($scope, $http, $routeParams, $location) {
            var url = '/api/memberconfirm/' + $routeParams.param1;
            $http.get(url)
                 .success(function(data, status, headers, config) {
                        /*
                             null means no user found? 
                        */
                        if(data) {
                             $location.path("/login");
                        }
                        else {
                             $location.path("/memberconfirmfailed");
                        }
                 })
                 .error(function(data, status, headers, config) {
                        alert("not ok");
                        // called asynchronously if an error occurs
                        // or server returns response with an error status.
                 });
      }
]);

REST 使用 HTTP 响应代码,因此404表示未找到。另外,请注意,如果未找到任何内容,猫鼬会返回null。它只返回实际错误(如数据库错误)的err

对于服务器端代码:

return db.userModel.findOne({...}, function(err, data) {
    if (err) { /* handle the error */ }
    else {
        if (data) { return res.send(data); }
        else { return res.send(404); }
    }        
});

对于客户端代码:

$http.get(url)
    .success(function(data, status, headers, config) {
      /* found: do stuff */
    })
    .error(function(data, status, headers, config) {
      if (status === 404) { /* not found */ }
      else { /* some other error to deal with */ }
    })
;

最新更新