To create a rest API from an Express NodeJS app just add a new js file to the routes folder, e.g. rest.js and add a call to to the app.js file:
var express = require('express'); var app = express(); app.use("/rest", rest.js) app.use('/rest', rest);
To create a function which is first called on all requests add the following:
/* executed on all requests */ router.use(function(req, res, next) { console.log("There was a new request"); // pass request on to our api next(); });
To create a GET method at /rest/yourMethod add the following to your rest.js file:
router.get('/yourMethod', function(req, res, next) { res.send('A return value'); });
Parameters can be read with req.params.your_param and the rest call needs to be modified for this to match something like this: ‘/yourMethod/:your_param’
To create a POST method at /rest/yourMethod:
router.post('/putPayload', function(req, res, next) { console.log(req.body.your_post_param); res.json( {result: "OK"} ); });
Note that req.body.your_post_param reads the parameter named your_post_param from the POST request.
A full example can be found on GitHub: https://github.com/ordsen/gsoc-preparation/tree/master/nodejs_server_example/interface
.