【问题标题】:Expressjs routing from angularjs routesExpressjs路由来自angularjs路由
【发布时间】:2016-03-20 21:35:45
【问题描述】:

我在调用从前端到后端的路由时遇到问题。

我在客户端使用 angularjs $state,所以示例 url 是

http://localhost:1234/areas/customer/edit/56e2f6345968f8b812052694

但是,当我在服务器端使用如下 $resouce 查询调用此路由时,它调用了不正确的服务器端路由。

我的工厂包含一个使用 $resource 调用服务器端的方法

 getCustomerByID: function(id, callback){
          var cb = callback || angular.noop;

          return Customer.query(id, function(success){
            return cb(success);
          }, function(error){
            return cb(error);
          }).$promise;
        }

客户是下面的服务

angular.module('xxx')
  .factory('Customer', function ($resource) {
    return $resource('/api/customer/:id/:controller', { id: '@_id' })
  });

GET的服务器路由如下

router.get('/', controller.index);
router.get('/:id', controller.show);

我需要用 id 打路线,但它似乎打到了第一个

任何想法可能是什么

干杯

【问题讨论】:

    标签: angularjs express


    【解决方案1】:

    路由按顺序处理,交换以下路由:

    router.get('/', controller.index);
    router.get('/:id', controller.show);
    

    到这里:

    router.get('/:id', controller.show);
    router.get('/', controller.index);
    

    发生这种情况是因为像 /api/customer/:id/ 这样的请求也只会匹配 /api/customer,因此它会在第一条路由上捕获。

    【讨论】:

    • 是的,试过了,但不高兴不应该重启 grunt 服务器?
    • 是的,尝试重新启动 - 上面的路由应该可以工作。
    • 仍然没有喜悦。将 id 传递给查询时,我尝试将其作为数组传递 [{id: id}] 但那也不起作用
    • 我认为问题不在于 Express,最后一件事(对于 Express)要检查 - 您是否在 controller.show 路由/操作中调用 next()?如果是这样,这会将请求传递到链中的下一个路由。我对角度知之甚少-您是否在任何地方引用:controller?此外,您是否在您的网络选项卡(浏览器控制台)中检查了 AJAX 请求正在访问正确的 URL?
    • 现在成功了,但必须覆盖客户端内的查询方法,因此查询:{方法:“GET”,isArray:false}。所以它现在击中服务器端,但不喜欢它,因为它不是一个数组。现在看来,它更像是一个 angularjs 问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-21
    相关资源
    最近更新 更多