Skip to content

Instantly share code, notes, and snippets.

@faceslog
Last active November 28, 2022 20:25
Show Gist options
  • Save faceslog/05c833fea23b9982cdee88428e5019b8 to your computer and use it in GitHub Desktop.
Save faceslog/05c833fea23b9982cdee88428e5019b8 to your computer and use it in GitHub Desktop.
Nodejs Middleware to Log HTTP API-Requests when working with an API without any doc :kappa:
const http = require("http");
const server = http.createServer((request, response) => {
const requestStart = Date.now();
let errorMessage = null;
let body = [];
request.on("data", chunk => {
body.push(chunk);
});
request.on("end", () => {
body = Buffer.concat(body);
body = body.toString();
});
request.on("error", error => {
errorMessage = error.message;
});
response.on("finish", () => {
const { rawHeaders, httpVersion, method, socket, url } = request;
const { remoteAddress, remoteFamily } = socket;
console.log(
JSON.stringify({
timestamp: Date.now(),
processingTime: Date.now() - requestStart,
rawHeaders,
body,
errorMessage,
httpVersion,
method,
remoteAddress,
remoteFamily,
url
})
);
});
process(request, response);
});
const process = (request, response) => {
setTimeout(() => {
response.end();
}, 100);
};
server.listen(8888);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment