code everywhere
technology, web services and applications

basic Node.js API server

posted on March 18, 2016, 1:18 am in js, nodejs

A very basic Node.js API server with NO external dependancies. With this you can get your API server up and running in no time.

// Super simple Node.js API Server ...
var http = require('http');
var 
fs = require('fs');
var 
PORT 8080;
var 
requestCount 0;

http.createServer(function(reqres) {

    
// Get IP address
    
var ip req.connection.remoteAddress;

    
// A GET request
    
var get = function(path) {
        return (
req.method.toLowerCase() == 'get' && req.url.toLowerCase().substr(0path.length) == path.toLowerCase());
    };

    
// A POST request
    
var post = function(path) {
        return (
req.method.toLowerCase() == 'post' && req.url.toLowerCase().substr(0path.length) == path.toLowerCase());
    };

    
// Sending a file (note: node.js is not designed to be a file server! )
    
var sendFile = function(filetype) {
        
fs.readFile(require('path').resolve(__dirnamefile), function(errdata) {
            if (
err) {
                
console.log("sendFile Error: "JSON.stringify(err));
                
res.writeHead(404, {
                    
"Content-Type""text/plain"
                
});
                
res.write("404 Not Found");
            } else {
                
res.writeHead(200, {
                    
'Content-Type'type,
                    
'Content-Length'data.length,
                    
'Access-Control-Allow-Origin''*'
                
});
                
res.write(data);
            }
            
res.end();
        });
        return 
true;
    };


    switch (
true) {

        
// Sending a file example ...
        
case (get("/index") || req.url == "/"):
            
sendFile('index.html''text/html');
            break;

            
// API response example ...
        
case (get("/api/test")):
            
res.writeHead(200, {
                
'Content-Type''application/json'
            
});
            
res.end(JSON.stringify({
                
message"hello"
            
}));
            break;

            
// Default response ...
        
default:
            
res.writeHead(200, {
                
'Content-Type''application/json'
            
});
            
res.end(JSON.stringify({
                
message"oops, nothing here!"
            
}));
    }

    
// Logging ...
    
console.log("Request - IP: "ip"URL: "req.url"(" requestCount ")");
    
requestCount++;

}).
listen(PORT);
console.log("Node server running on " PORT " ...");

recent posts

< back