-
-
Save Bwvolleyball/c6315f3a744d2e3f52fece0cfd121dca to your computer and use it in GitHub Desktop.
Simple Request echo-ing Node Application
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 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