Here's a simple Node.js application that creates a REST api that you can post JSON to:
app.js:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));
var router = express.Router();
function dataHandler(req, res) {
// the 'body' variable will contain the json you've POSTed:
var body = req.body;
// your socket.io logic would go around here.
console.log(body.message);
res.send("ok");
}
router.route('/receive')
.post(dataHandler);
app.use('/api', router);
app.listen(3000, function() {
console.log('Express started at port 3000');
});
package.json:
{
"name": "node-test",
"descirption": "Node test",
"version": "0.0.1",
"private": true,
"dependencies": {
"body-parser": "^1.10.0",
"express": "^4.4.3"
}
}
To get it working, follow these steps (assuming here that you have Node installed):
- Create a new directory, and create the two above files in it
- run
npm install
. this will read package.json
and install the required dependencies
- run
node app.js
Send to URL http://localhost:3000/api/receive
the following JSON message with POST:
{
"message": "Hello world"
}
Check the console output where you ran the node app.js
. it should have logged the "Hello world" message.
What you're creating is a simple REST api. To learn more about how to do REST apis with Node.js and gain understanding of what's going on in the example app I posted, you can Google 'Node.js rest api tutorial'. You'll typically have to cherry-pick what you read as some of the tutorials will explain how to set up database, etc. Here's one that goes through most of what is done in the example above.