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.
  1. {
  2. "user1" : {
  3. "name" : "mahesh",
  4. "password" : "password1",
  5. "profession" : "teacher",
  6. "id": 1
  7. },
  8. "user2" : {
  9. "name" : "suresh",
  10. "password" : "password2",
  11. "profession" : "librarian",
  12. "id": 2
  13. },
  14. "user3" : {
  15. "name" : "ramesh",
  16. "password" : "password3",
  17. "profession" : "clerk",
  18. "id": 3
  19. }
  20. }
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.
  1. var express = require('express');
  2. var app = express();
  3. var fs = require("fs");
  4. var bodyParser = require('body-parser');
  5. //enable CORS for request verbs
  6. app.use(function(req, res, next) {
  7. res.header("Access-Control-Allow-Origin", "*");
  8. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  9. res.header("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, OPTIONS");
  10. next();
  11. });
  12. app.use(bodyParser.urlencoded({
  13. extended: true
  14. }));
  15. app.use(bodyParser.json());
  16. //Handle GET method for listing all users
  17. app.get('/listUsers', function (req, res) {
  18. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
  19. console.log( data );
  20. res.end( data );
  21. });
  22. })
  23. //Handle GET method to get only one record
  24. app.get('/:id', function (req, res) {
  25. // First read existing users.
  26. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
  27. users = JSON.parse( data );
  28. console.log(req.params.id);
  29. var user = users["user" + req.params.id]
  30. console.log( user );
  31. res.end( JSON.stringify(user));
  32. });
  33. })
  34. //Handle POST method
  35. app.post('/addUser', function (req, res) {
  36. // First read existing users.
  37. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
  38. var obj = JSON.parse('[' + data + ']' );
  39. obj.push(req.body);
  40. console.log(obj);
  41. res.end( JSON.stringify(obj) );
  42. });
  43. })
  44. //Handle DELETE method
  45. app.delete('/deleteUser/:id', function (req, res) {
  46. // First read existing users.
  47. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
  48. data = JSON.parse( data );
  49. delete data["user" + req.params.id];
  50. console.log( data );
  51. res.end( JSON.stringify(data));
  52. });
  53. })
  54. //Handle GET method
  55. app.put('/updateUser/:id', function(req,res){
  56. // First read existing users.
  57. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
  58. //var obj = JSON.parse('[' + data + ']' );
  59. data = JSON.parse( data );
  60. var arr={};
  61. arr=req.body;
  62. data["user" + req.params.id]= arr[Object.keys(arr)[0]] ; // req.body; //obj[Object.keys(obj)[0]]
  63. res.end( JSON.stringify( data ));
  64. });
  65. } );
  66. var server = app.listen(8081, function () {
  67. var host = server.address().address
  68. var port = server.address().port
  69. console.log("Example app listening at http://%s:%s", host, port)
  70. })
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 [ ].
  1. 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.