Created
December 10, 2017 23:16
-
-
Save niamurrell/87d8b7e120491c52f75f08acde2c7b5f to your computer and use it in GitHub Desktop.
Runs a Node.js server which stores/retrieves data in memory based on URL params
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
var http = require("http"); | |
var url = require("url"); | |
var db = {}; | |
var handleRequest = function(req, res) { | |
res.writeHead(200, {"Content-Type": "text/plain"}); | |
console.log("Request was made to URL: " + req.url); | |
// Get URL params | |
var parsedUrl = url.parse(req.url, true); | |
var pathname = parsedUrl.pathname; | |
var query = parsedUrl.query; | |
var resMessage = "Proper URL params: '/set?somekey=somevalue' OR '/get?key=somekey'"; | |
// Handle routes | |
if (pathname === "/set") { // SET sends params to JSON object | |
db = Object.assign(db, query); | |
resMessage = "You have stored " + JSON.stringify(query) + " in memory."; | |
console.log(db); | |
} else if (pathname === "/get") { // GET finds params from JSON object | |
var key = query.key; | |
var value = db[key]; | |
resMessage = "The value of '" + key + "' is: " + value; | |
} | |
// Send result to user | |
res.end(resMessage); | |
} | |
// Run server | |
http.createServer(handleRequest).listen(4000, function() { | |
console.log("App running on port 4000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment