Created
April 15, 2021 11:39
-
-
Save joe-oli/7794a9e154ebd99c808abcbe8034a590 to your computer and use it in GitHub Desktop.
Basic Barebones "Raw" node.js server
This file contains hidden or 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
//definitely barebones -- using node's native http.createServer | |
require('http').createServer((req, res) => { | |
let statusCode = 404 | |
let data = {status: 404} | |
const chunks = [] | |
req.on('error', (err) => { | |
console.error(err); | |
}) | |
req.on('data', (chunk) => { | |
chunks.push(chunk.toString()) | |
}) | |
req.on('end', () => { | |
const payload = chunks.join('') | |
if (req.method === 'GET' && req.url === '/') { | |
statusCode = 200 | |
data = {hello: "world"} | |
} | |
if (req.method === 'POST' && req.url === '/echo') { | |
statusCode = 200 | |
data = JSON.parse(payload) | |
} | |
const body = JSON.stringify(data) | |
res.writeHead(statusCode, { | |
'Content-Type': 'application/json', | |
'Content-Length': body.length | |
}) | |
res.end(body); | |
}) | |
}).listen(3000); | |
/* | |
Of course, this makes a lot of assumptions about the data you're posting -- and will die in a fire if you pass it invalid json. | |
And that's just two routes - I suppose this is why frameworks exist. | |
Don't be a food + re-invent the wheel, use Express ! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment