Skip to content

Instantly share code, notes, and snippets.

@marcogrcr
Created May 22, 2024 20:41
Show Gist options
  • Save marcogrcr/454e3208d57f0a924161b3b33a4ac8fe to your computer and use it in GitHub Desktop.
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
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