快递路由器无法正确解析路径

时间:2015-01-25 01:07:44

标签: javascript node.js express

我正在处理一个应用程序。在该应用程序中,我在配置文件中定义了所有路由,并创建了一个中间件来加载所有路由。

以下是中间件代码

var loadRoutes = function(router, config, controllers) {
  var route, routeValues, routeKeys, verb,
    path, controllerName, actionName, actionMethod;

  //load and initialize secured routes
  for (route in config.routes.secured) {
    if (config.routes.secured.hasOwnProperty(route)) {
      routeValues = config.routes.secured[route].split('#');
      if (routeValues.length !== 2) {
        throw new Error('ERROR Route value "' + config.routes.secured[route] + 
          '" Route value must be "<controller-name>#<action-method-name>",' + ' like "foo#index"');
      }

      routeKeys = route.split(' ');
      if (routeKeys.length !== 2) {
        throw new Error('ERROR Route key "' + route + '" Route key must be "<HTTP-verb> <path-pattern>", like "GET /foo/:id"');
      }

      verb = routeKeys[0];
      path = routeKeys[1];
      controllerName = routeValues[0];
      actionName = routeValues[1];
      if (!routingMethods[verb]) {
        throw new Error('HTTP verb "' + verb + '" for route "' + route + '" is not supported!');
      }

      if (!controllers[controllerName]) {
        throw new Error('Controller "' + controllerName + '" is not available for route "' + route + '"!');
      }

      actionMethod = controllers[controllerName][actionName];
        if (!actionMethod) {
          throw new Error('Action method "' + controllerName + '#' + actionName + '" is not available for route "' + route + '"!');
      }
      console.log(routingMethods[verb]);
      console.log(path);
      router[routingMethods[verb]](path, auth(), controllers[controllerName][actionName]);
    }
  }
};

路由器是express.Router();

的实例

我将路线配置定义为

{
  "routes": {
    "secured": {
      "GET /users/me": "UserController#getMyUserProfile",
      "PUT /users/me": "UserController#updateCurrentUserProfile",
      "POST /forgotPassword": "UserController#recoverPassword",
      "POST /resetPassword": "UserController#resetPassword",
      "GET /users/:id": "UserController#getUserProfile",
    }
  }
}

现在,当我发送/users/me请求时,请求将转到/users/:id控制器方法。为什么会这样?

我在/users/me

之前定义了/users/:id路线

编辑: 添加routingMethods变量

var routingMethods = {
  GET: 'get',
  POST: 'post',
  PUT: 'put',
  DELETE: 'delete',
  HEAD: 'head',
  OPTIONS: 'options'
};

0 个答案:

没有答案