Last active
June 14, 2020 21:40
-
-
Save AD0791/dd99af60f6963ca17a41eb7e29fff89f to your computer and use it in GitHub Desktop.
nodejs server with request event listener
This file contains hidden or 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
// npm init | |
// npm i http -S | |
// npm i http-status-codes -S | |
const port = 9000; | |
http = require('http'); | |
httpStatus = require('http-status-codes'); | |
app = http.createServer(); | |
const getJSONString = obj => { | |
return JSON.stringify(obj, null, 2); | |
}; | |
// event listener | |
app.on('request', (req, res) => { | |
res.writeHead(httpStatus.OK, { | |
'Content-Type': 'text/html' | |
}); | |
let resMessage = ` | |
<style> | |
h1{ | |
display: flex; | |
align-items: center; | |
justify-content: center; | |
} | |
</style> | |
<h1>Hello Node server</h1>`; | |
res.end(resMessage); | |
console.log(`Method: ${getJSONString(req.method)}`); | |
console.log(`url: ${getJSONString(req.url)}`); | |
console.log(`headers: ${getJSONString(req.headers)}`); | |
}); | |
// run server | |
app.listen(port); | |
console.log(`server is active: ${port}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment