-
-
Save hpfast/4ff6a5e64f92690624263d909e497d57 to your computer and use it in GitHub Desktop.
Simple NodeJS web server example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************ | |
FILENAME | |
server_simple.js | |
DESCRIPTION | |
creates a simple web server that | |
displays translations of requested words | |
HOW TO START SERVER: | |
1) from terminal run 'node simple_server.js' | |
2) open web browser visit http://127.0.0.1:8080 | |
*************************************************/ | |
// Include the HTTP Node library | |
// http://nodejs.org/docs/latest/api/http.html | |
var http = require('http'); | |
// define the IP and port number | |
var localIP = "127.0.0.1"; // 127.0.0.1 is used when running the server locally | |
var port = 8080; // port to run webserver on | |
function sayHello(req, res) { | |
// HTTP response header - the content will be JSON mimetype | |
res.writeHead(200, {'Content-Type': 'application/json'}); | |
if (req.url === '/hello') { | |
res.write(JSON.stringify({ | |
hello: 'hoi', | |
language: 'NL' | |
})) | |
} else if (req.url === '/goodbye') { | |
res.write(JSON.stringify({ | |
goodbye: 'doei', | |
language: 'NL' | |
})) | |
} | |
// End of HTTP response | |
res.end(); | |
} | |
/************************/ | |
/* START THE SERVER */ | |
/************************/ | |
// Create the HTTP server | |
var server = http.createServer(sayHello); | |
// Turn server on - now listening for requests on localIP and port | |
server.listen(port, localIP); | |
// print message to terminal that server is running | |
console.log('Server running at http://'+ localIP +':'+ port +'/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment