Created
May 9, 2023 13:39
-
-
Save JuninhoFreitas/d7a6ef58c45149d62dd0025951d96bc1 to your computer and use it in GitHub Desktop.
An endpoint just to return what u have sent, using only native features.
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 http = require('http'); | |
const port = 3349 | |
const routes = { | |
'/': handlePostReq | |
} | |
const server = http.createServer((req, res) => { | |
routes[req.url](req, res); | |
}) | |
function handlePostReq(req, res) { | |
const size = parseInt(req.headers['content-length'], 10) | |
const buffer = Buffer.allocUnsafe(size) | |
var pos = 0 | |
req.on('data', (chunk) => { | |
const offset = pos + chunk.length | |
if (offset > size) { | |
reject(413, 'Too Large', res) | |
return | |
} | |
chunk.copy(buffer, pos) | |
pos = offset | |
}) | |
.on('end', () => { | |
if (pos !== size) { | |
reject(400, 'Bad Request', res) | |
return | |
} | |
const data = JSON.parse(buffer.toString()) | |
res.setHeader('Content-Type', 'application/json;charset=utf-8'); | |
res.end(JSON.stringify(data)) | |
}) | |
} | |
server.listen(port, () => { | |
console.log(`Server listening on port ${port}`); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment