Skip to content

Instantly share code, notes, and snippets.

@nickbalestra
Last active January 19, 2019 02:54
Show Gist options
  • Save nickbalestra/5c904e9cbe218ec6649c to your computer and use it in GitHub Desktop.
Save nickbalestra/5c904e9cbe218ec6649c to your computer and use it in GitHub Desktop.
Building a simple node server. Blog post: http://nick.balestra.ch/2015/build-a-simple-api-server-with-node/
var utils = require('../utils');
var actions = {
'GET': function(request, response){
utils.respond(response, 'Pong');
}
// 'POST': function(request, response){},
// 'PUT': function(request, response){},
// 'DELETE': function(request, response){},
// 'OPTIONS': function(request, response){}
};
exports.requestHandler = utils.actionDispatcher(actions);
var url = require('url');
var utils = require('./utils');
// The routes hash maps registered endpoint URLs
// with their relative handler modules.
var routes = {
'/ping' : require('./endPointHandlers/ping')
};
// The router module check the url of the request
// against the routes hash and route the request to its
// relative handler. If the requested endpoint
// isn't a valid registered route a 404
// reponse will be sent back instead.
module.exports = function(request, response) {
var routeHandler = routes[url.parse(request.url).pathname];
if (routeHandler){
routeHandler.requestHandler(request, response);
} else {
utils.respond(response, 'Oups', 404);
}
};
var http = require('http');
var router = require('./router');
var port = 3000;
var ip = '127.0.0.1';
var server = http.createServer(router);
server.listen(port, ip);
var headers = {
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "content-type, accept",
"access-control-max-age": 10, // Seconds.
'Content-Type': "application/json"
};
exports.respond = function(response, data, statusCode){
statusCode = statusCode || 200;
response.writeHead(statusCode, headers);
response.end(JSON.stringify(data));
};
exports.fetchData = function(request, callback){
var data = "";
request.on('data', function(chunk){
data += chunk;
});
request.on('end', function(){
callback(JSON.parse(data));
});
};
exports.actionDispatcher = function(actionsHash){
return function(request, response) {
var action = actionsHash[request.method];
if (action) {
action(request, response);
} else {
exports.respond(response, '', 404);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment