【问题标题】:How to GET data from serverside (using mongoose) to clientside depending on the $stateparams in Angularjs如何根据Angularjs中的$ stateparams从服务器端(使用猫鼬)获取数据到客户端
【发布时间】:2016-10-28 19:04:09
【问题描述】:

所以我的应用程序中有一个用户列表,其中有一个由 mongoDB 自动设置的唯一 _id,我想要做的是使用 $stateParams 根据其 _id 在单独的页面中显示特定用户的详细信息,例如例如,如果网址是

http://localhost/project/users/576a5392357753bc22982cb9

并在此特定页面中显示具有该576a5392357753bc22982cb9 id 的用户详细信息。但我收到 404 错误。请帮助我还是 MEAN 堆栈的新手,如果您需要更多我的代码,我会提供它来帮助它解决问题,如果有更多“具体和正确的方法”,请告诉我。谢谢!

AngularJS 控制器:

.controller("userDetailsCtrl", function($scope, $stateParams){

               $http.get('http://localhost:3000/api/specificProfle', {
                      params: { id: $stateParams.id}
              })
               .then(function(success) {
                      $scope.datalist = success.data;
                      console.log($scope.datalist);
               })
               .catch(function(error) {
                      console.error(error);
               });
});

路线:

.state('userDetails', {
        url: '/users/:id',
        templateUrl: 'scripts/components/user-details/userDetails.html',
        controller: "userDetailsCtrl"
    })

ExpressJS API:

router.get('/api/specificProfile', ensureAuthenticated, function(req, res) {
          Users.findOne({ _id : req.params._id}, function(err, user) {
                    res.send(user);
                    console.log(user);
          });
});

用户 HTML 列表

<div class="container">
<h3>Users</h3>

<div class="table-responsive">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Username</th>
                <th>Email Address</th>
                <th>Name</th>
                <th>Phone Number</th>
                <th>Role</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat='user in datalist'>
                <td>
                    <a ui-sref="userDetails({id: user._id})" data-ng-hide="editMode">{{user.username}}</a>
                    <input type="text" data-ng-show="editMode" ng-model="user.username" />
                </td>
                <td>
                    <span data-ng-hide="editMode">{{user.email}}</span>
                    <input type="text" data-ng-show="editMode" ng-model="user.email" />
                </td>
                <td>
                    <span data-ng-hide="editMode">{{user.name}}</span>
                    <input type="text" data-ng-show="editMode" ng-model="user.name" />
                </td>
                <td>
                    <span data-ng-hide="editMode">{{user.phoneNumber}}</span>
                    <input type="text" data-ng-show="editMode" ng-model="user.phoneNumber">
                </td>
                <td>
                    <span data-ng-hide="editMode">{{user.role}}</span>
                    <select class="form-control" data-ng-show="editMode" ng-model="user.role">
                        <option>Administrator</option>
                        <option>Advertiser</option>
                        <option>Subscriber</option>
                    </select>
                </td>
                <td>
                    <a a-href="" class="glyphicon glyphicon-pencil" data-ng-hide="editMode" data-ng-click="editMode = true"></a>
                    <a a-href="" class="glyphicon glyphicon-ok" data-ng-show="editMode" data-ng-click="editMode = false; update(user)"></a>
                    <a a-href="" class="glyphicon glyphicon-remove" data-ng-show="editMode" data-ng-click="editMode = false"></a>
                </td>
            </tr>
        </tbody>
    </table>
</div>
<div>
    <a class="btn btn-primary" role="button" ui-sref="user">Add New User</a>
</div>

在哪里

ui-sref="userDetails({id: user._id})"

将处理指向 userDetails 页面的链接,该页面将具有 url/状态,无论用户的 _id 在用户列表页面中是什么

编辑

我发现这只是控制器中的一个错字,应该是

http://localhost:3000/api/specificProfile

而不是

http://localhost:3000/api/specificProfle

个人资料中缺少“i”。

现在没有更多错误,但它抛出 Null,也许我的 mongoose 查询有问题?

【问题讨论】:

  • '但我收到 404 错误'.. 你收到什么错误消息?
  • 在控制器中我的 $http 请求中,在 .catch Object {data: "

    Not Found

    404

    Error : Not Fo...\node_modules\serve-static\index.js:120:7)
    ↵",状态:404,配置:对象,状态文本:“未找到”}
  • 你的路由器符合这个npmjs.com/package/router#api
  • 因为您的 API 似乎无法正常工作,并且当它尝试调用它时,找不到该 API 的打开链接

标签: angularjs express mongoose mean-stack


【解决方案1】:

所以有几种不同的方法可以做到这一点,我会这样做:

快速路由器:

router.get('/api/:userId', ensureAuthenticated, function(req, res) {
      Users.findOne({ _id : req.params.userId}, function(err, user) {
                res.send(user);
                console.log(user);
      });
});

另一种方式是使用express中间件:

router.get('/api/:userId', ensureAuthenticated, function(req, res) {
      res.send(req.userProfile);
});

和中间件绑定

app.param('userId', users.userByID);


exports.userByID = function(req, res, next, id) {
    Users.findOne({ _id : req.params.userId}, function(err, user) {
      if (err) return next(err);
      if (!user) return next(new Error('Failed to load User ' + id));
      req.userProfile = user;
      next();
    });
};

【讨论】:

  • 尝试您的第一种方法后出现此错误{ [CastError: Cast to ObjectId failed for value ":id" at path "_id"] message: 'Cast to ObjectId failed for value ":id" at path "_id"', name: 'CastError', kind: 'ObjectId', value: ':id', path: '_id', reason: undefined }
  • 你能 console.log(req.params.userId) 吗?
  • 你的请求格式应该是这样的:GET localhost:3000/api/576a5392357753bc22982cb9
  • 是的,我所做的是将 /:id 放在控制器和 API 中的 $http 请求的末尾。我也试过玩 /:_id 等但没有运气。
  • 你能在 route.get 中使用 console.log(req.params.userId) 吗?
猜你喜欢
  • 2020-08-16
  • 2020-08-11
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多