-
-
Save fijiwebdesign/b3d2cab209e739bcdc0a9fec615c3ce1 to your computer and use it in GitHub Desktop.
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'); | |
let server = http.createServer(); | |
server.on('request', (request, response) => { | |
let {method, url, headers} = request; | |
console.log(`Received ${method} request for "${url}".`); | |
for (let headerName of Object.keys(headers)) { | |
let headerValue = headers[headerName]; | |
console.log(` ${headerName}: ${headerValue}`); | |
} | |
let bytesReceived = 0; | |
request.on('data', (chunk) => { | |
bytesReceived += chunk.length; | |
console.log(`Received ${chunk.length} bytes of the request body.`); | |
}); | |
request.on('end', () => { | |
console.log(`Request has completed. Sending response.`); | |
response.setHeader('Content-Type', 'text/plain'); | |
response.write(`Thank you for your ${method} request for "${url}".\n`); | |
if (bytesReceived === 0) { | |
response.write(`There was no request body.\n`); | |
} else { | |
response.write(`Received request body of size ${bytesReceived} bytes.\n`); | |
} | |
response.end(); | |
}); | |
request.on('error', (error) => { | |
console.log(`There was an error receiving the request.`); | |
console.error(error.stack); | |
}); | |
}); | |
server.on('listening', () => { | |
let {port} = server.address(); | |
console.log(`HTTP server listening on port ${port} ...`); | |
}); | |
server.listen(5100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment