如何在Express.JS中处理同一个Controller的不同动作?

Dai*_*ail 3 node.js express

我有很多路线,如:

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

app.get("page2/:action", function(req, res) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

在哪里page1page2是两个控制器,这:action是我需要调用的"方法".页面应该是:

  1. /第1页/删除
  2. /第1页/修改
  3. /第1页/加

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

谢谢!

ale*_*lex 5

这是一个如何实现这一目标的例子.您可以在Expressjs指南上阅读更多相关内容:http://expressjs.com/guide/error-handling.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;
});
Run Code Online (Sandbox Code Playgroud)

  • 你有什么特别的理由不想确认REST设计吗?例如,为什么不使用http DELETE方法删除记录?有关详情,请访问http://en.wikipedia.org/wiki/Representational_state_transfer (4认同)