In your routes folder(if you are using express-gen) or anywhere else create a node module which uses express.router()
as follows
var express = require('express');
var bodyParser = require('body-parser');
var dishRouter = express.Router();
dishRouter.use(bodyParser.json());
Then handle your requests, example:
dishRouter.route('/')
.get(function(req, res, next) {
res.end('Will send all the dishes to you!');
})
.post(function(req, res, next) {
res.end('Will add the dish: ' + req.body.name + ' with details: ' + req.body.description);
});
And use this in ur app.js or the main file which you run:
var express = require('express');
var path = require('path');
var dishRouter=require('./routes/dishRouter');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use('/dishes',dishRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
res.redirect('/fail');
next(err);
});
So what this will do is that, it will handle the get and post requests from client for URI /dishes
and for others, it will throw an error 404 and send to /fail
path.