Reputation: 4606
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:
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!
Upvotes: 4
Views: 2990
Reputation: 63653
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;
});
Upvotes: 6