Skip to content

Instantly share code, notes, and snippets.

@ankurshukla
Last active December 20, 2015 21:28
Show Gist options
  • Save ankurshukla/6197500 to your computer and use it in GitHub Desktop.
Save ankurshukla/6197500 to your computer and use it in GitHub Desktop.
basic HTTP JSON server using NodeJS. Ideal for backend data test for mobile or web UI
var test = require('./test');
function route(pathname){
var data;
pathname = pathname.substring(1, pathname.length);
switch(pathname){
case "somethingrandom" :
data = {
'something random' : 'true',
'something truly random' : 'true'
};
break;
case "test" :
data = test.returnSomeData();
break;
default:
data = {'error' : 'incorrect endpoint'};
}
return data;
}
module.exports.route = route;
//server.js
var http = require('http');
var router = require('./router'); //router file
function processIncomingRequest(req, res){
console.log("INCOMING REQUEST: "+req.method+ " "+ req.url);
var response = router.route(req.url);
res.writeHead(200,{
'Content-Type' : 'application/json',
'Content-Length' : response.length
});
res.end(JSON.stringify(response) + "\n");
}
var server= http.createServer(processIncomingRequest);
server.listen(8080);
function returnSomeData(){
var jsonData = {
'item-1' : 'a table',
'item-2' : 'a phone',
'item-3' : 'a coffee mug',
'item-4' : 'a mouse device',
'item-5' : 'a sunglass',
'item-6' : 'a necktie',
};
return jsonData;
}
module.exports.returnSomeData = returnSomeData;
@ankurshukla
Copy link
Author

in the above code snippet, to use it as a backend REST Endpoint, following needs to be done:

//1. create a new js file with a function that returns the JSON Data (Similar to test.js) and dont forget to module export the method that returns the json data

//2. in router.js add another case with the endpoint as the evaluating expression (like for localhost:8080/newEndpoint) the evaluating expression will be newEndpoint. Also dont forget to include you new js file vai require statement

//3. inside the case (like test in router.js), call the new function and assign the returning JSON to the variable 'data'

Thats it! you are done!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment