Last active
July 2, 2020 08:25
-
-
Save DyadicGit/49be366060205375f4fc28346980e526 to your computer and use it in GitHub Desktop.
basic node.js server with GET endpoints & without express
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
const https = require('https'); | |
callback = returnFn => response => { | |
let str = ''; | |
response.on('data', chunk => { | |
str += chunk; | |
}); | |
response.on('end', () => { | |
returnFn(str); | |
}); | |
} | |
const backup = (value) => console.log(value) | |
const getHtmlDoc = (url, returnFn = backup) => https.request(url, callback(returnFn)).end(); | |
const http = require('http'); | |
http.createServer((req, res) => { | |
const sendJson = (data) => { | |
res.writeHead(200, {'Content-Type': 'application/json'}); | |
res.write(JSON.stringify(data) ); | |
res.end(); | |
} | |
const sendHtml = (data) => { | |
res.writeHead(200, {'Content-Type': 'text/html'}); | |
res.write(data); | |
res.end(); | |
} | |
switch (req.url) { | |
case '/wiki': | |
getHtmlDoc('https://www.wikipedia.org/', sendHtml) | |
break | |
case '/json-data': | |
sendJson({ data: [1,2,3] }) | |
break | |
default: | |
sendHtml('<h1>Hello World!</h1>') | |
} | |
}).listen(3000, () => { | |
console.log("server start at port http://localhost:3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment