문제

I have many routes like:

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

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

where page1 and page2 are two controllers and the :action is the "method" I need to call. The pages should be:

  1. /page1/delete
  2. /page1/modify
  3. /page1/add

I try to organize my code to simplify the job following a MVC system. Could someone give me an advice regarding, how can I call the method of a controller by reading the parameter I use as :action I need to check if the method exists if not (if someone write /page1/blablabla) I return a 404 http error.

Thank you!

도움이 되었습니까?

해결책

Here's an example on how to achieve this. You can read more on this on the Expressjs guide: 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;
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top