Skip to content

Instantly share code, notes, and snippets.

@AD0791
Last active June 14, 2020 21:40
Show Gist options
  • Save AD0791/dd99af60f6963ca17a41eb7e29fff89f to your computer and use it in GitHub Desktop.
Save AD0791/dd99af60f6963ca17a41eb7e29fff89f to your computer and use it in GitHub Desktop.
nodejs server with request event listener
// 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