Created
May 22, 2024 20:41
-
-
Save marcogrcr/454e3208d57f0a924161b3b33a4ac8fe to your computer and use it in GitHub Desktop.
A simple node.js HTTP/1.1 server that echoes back a request as a JSON object
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
import { createServer } from "http"; | |
const server = createServer((req, res) => { | |
const { method, url: path, headersDistinct: headers } = req; | |
let data = []; | |
req.on("data", (chunk) => data.push(chunk)); | |
req.on("end", (chunk) => { | |
data.push(chunk); | |
data = data.join(""); | |
let json; | |
try { | |
json = JSON.parse(data); | |
} catch {} | |
res.appendHeader("content-type", "application/json"); | |
res.write( | |
JSON.stringify( | |
{ | |
method, | |
path, | |
headers, | |
body: json ?? data, | |
}, | |
null, | |
2 | |
) | |
); | |
res.end(); | |
}); | |
}); | |
server.listen(8080); | |
console.log("Server started!"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment