Skip to content

Instantly share code, notes, and snippets.

@Bwvolleyball
Created March 22, 2022 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bwvolleyball/c6315f3a744d2e3f52fece0cfd121dca to your computer and use it in GitHub Desktop.
Save Bwvolleyball/c6315f3a744d2e3f52fece0cfd121dca to your computer and use it in GitHub Desktop.
Simple Request echo-ing Node Application
const http = require('http');
const server = http.createServer();
// create an echo function that logs the request & body,
// and responds with a 2xx status code and OK.
const echo = (request, response, body) => {
body = Buffer.concat(body).toString();
console.log('\nReceived Request:\n')
console.log(`${request.method}: ${request.url}`);
console.log('\nHeaders:');
console.log(request.headers);
console.log('\nBody:');
if (request.headers['content-type'] === 'application/json') {
// pretty print the body if it's JSON.
console.log(JSON.stringify(JSON.parse(body), null, 2));
} else {
// otherwise, just show us what we got.
console.log(body);
}
response.statusCode = request.method.match(/^(POST|PUT|DELETE)$/) ? 202 : 200;
response.write('OK\n');
response.end();
};
// start the node server on a specific port, and echo all requests sent to the server.
server.on('request', (request, response) => {
let body = [];
request.on('data', (chunk) => body.push(chunk))
.on('end', () => echo(request, response, body));
}).listen(process.env.SERVER_PORT || 8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment