Skip to content

Instantly share code, notes, and snippets.

@hpfast
Forked from johnschimmel/server_simple.js
Created April 4, 2019 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hpfast/4ff6a5e64f92690624263d909e497d57 to your computer and use it in GitHub Desktop.
Save hpfast/4ff6a5e64f92690624263d909e497d57 to your computer and use it in GitHub Desktop.
Simple NodeJS web server example
/************************************************
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