我有很多路线,例如:

//routes
app.get("page1/:action", function(req, res) {
  ...
}

app.get("page2/:action", function(req, res) {
  ...
}

在哪里 page1page2 是两个控制器, :action 是我需要打电话的“方法”。页面应该是:

  1. /page1/删除
  2. /page1/修改
  3. /page1/添加

我尝试组织我的代码以简化MVC系统之后的工作。有人可以给我一个建议,我如何通过阅读我用作的参数来称呼控制器的方法 :action 我需要检查该方法是否存在(如果有人写) /page1/blablabla)我返回404 HTTP错误。

谢谢!

有帮助吗?

解决方案

这是如何实现这一目标的示例。您可以在ExpressJS指南中了解更多信息: http://expressjs.com/guide/error andling.html

function NotFound(msg){
  this.name = 'NotFound';
  Error.call(this, msg);
  Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;

//routes
app.get("page1/:action", function(req, res) {
  switch(req.params.action) {
    case 'delete':
      // delete 'action' here..
      break;
    case 'modify':
      // delete 'modify' here..
      break;
    case 'add':
      // delete 'add' here..
      break;
    default:
      throw new NotFound(); // 404 since action wasn't found
      // or you can redirect
      // res.redirect('/404');
  }
}

app.get('/404', function(req, res){
  throw new NotFound;
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top