In this blog, I want to show you how to create a fake REST API Server, using Node.js. This will be just a Server to test AJAX at your client side.
Here is a blog, I benefitted from, and modified the code. In addition to it, it added support for CORS and request verbs like (POST, GET, DELETE, PUT).
First of all, create a folder (RESTAPI) and create a JSON file, as shown below. I used the file mentioned in the link above for sample JSON data.
- {
- "user1" : {
- "name" : "mahesh",
- "password" : "password1",
- "profession" : "teacher",
- "id": 1
- },
- "user2" : {
- "name" : "suresh",
- "password" : "password2",
- "profession" : "librarian",
- "id": 2
- },
- "user3" : {
- "name" : "ramesh",
- "password" : "password3",
- "profession" : "clerk",
- "id": 3
- }
- }
From start menu, open Node.Js command prompt and change the directory, where our folder is located and type the command given below.
npm install express --save
Create a JavaScript file, add the piece of code and name it server.js.
- var express = require('express');
- var app = express();
- var fs = require("fs");
- var bodyParser = require('body-parser');
-
- //enable CORS for request verbs
- app.use(function(req, res, next) {
- res.header("Access-Control-Allow-Origin", "*");
- res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
- res.header("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, OPTIONS");
- next();
- });
-
- app.use(bodyParser.urlencoded({
- extended: true
- }));
-
- app.use(bodyParser.json());
-
- //Handle GET method for listing all users
- app.get('/listUsers', function (req, res) {
- fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
- console.log( data );
- res.end( data );
- });
- })
-
- //Handle GET method to get only one record
- app.get('/:id', function (req, res) {
-
- fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
- users = JSON.parse( data );
- console.log(req.params.id);
- var user = users["user" + req.params.id]
- console.log( user );
- res.end( JSON.stringify(user));
- });
- })
-
- //Handle POST method
- app.post('/addUser', function (req, res) {
-
- fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
- var obj = JSON.parse('[' + data + ']' );
- obj.push(req.body);
- console.log(obj);
-
- res.end( JSON.stringify(obj) );
- });
- })
-
- //Handle DELETE method
- app.delete('/deleteUser/:id', function (req, res) {
-
-
- fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
- data = JSON.parse( data );
-
- delete data["user" + req.params.id];
-
- console.log( data );
- res.end( JSON.stringify(data));
- });
- })
-
- //Handle GET method
- app.put('/updateUser/:id', function(req,res){
-
-
- fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
-
- data = JSON.parse( data );
- var arr={};
- arr=req.body;
-
- data["user" + req.params.id]= arr[Object.keys(arr)[0]] ;
-
- res.end( JSON.stringify( data ));
-
- });
- } );
-
- var server = app.listen(8081, function () {
-
- var host = server.address().address
- var port = server.address().port
-
- console.log("Example app listening at http://%s:%s", host, port)
-
- })
Notice
The parameter (data) of the request handler method is supposed to be an array of JSON objects but it didn't accept the normal array methods like (
push) method, so I decided to parse it with the brackets [ ].
- var obj = JSON.parse('[' + data + ']' );
To run this Server, open node.js command prompt and run the command.
$ node server.js
Now, the Server is running and now you have a REST API Server, which supports CORS for the requests.
Here, it is listening at port 8081. To test our Server, this is the sample data for the testing purpose.
Here, it is listening at port 808. To test our Server, this is a sample data for the testing purpose.
Method |
Route |
Payload/Data |
|
GET |
http://IP:8081/listUsers |
GET id |
http://IP:8081/5 |
POST |
http://IP:8081/addUser |
{ "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } |
DELETE |
http://IP:8081/deleteUser/4 |
{ "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } |
PUT |
http://Ip:8081/updateUser/4 |
{ "user4" : { "name" : "Ahmed", "password" : "password5", "profession" : "QC engineer", "id": 4 } } |
I hope it comes in handy.