Created
May 26, 2023 16:01
-
-
Save sjfricke/2728b76510d2f453fd3675bd3d76f04c to your computer and use it in GitHub Desktop.
Simpler Server Port Demo
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
<html> | |
<head> | |
<style> | |
body {background-color: powderblue;} | |
h1 {color: blue;} | |
</style> | |
</head> | |
<body onload="GetMagicNumber()"> | |
<h1 id="message"></h1> | |
</body> | |
<script> | |
function RequestListener() { | |
const value = JSON.parse(this.responseText).value; | |
document.getElementById('message').innerHTML = value; | |
} | |
function GetMagicNumber() { | |
const req = new XMLHttpRequest(); | |
req.addEventListener("load", RequestListener); | |
req.open("GET", "/getNumber"); | |
req.send(); | |
} | |
</script> | |
</html> |
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 magic_number = 45; | |
const port = 8000; | |
// | |
// ----------------- | |
// | |
const fs = require('fs') | |
const http = require("http"); | |
const requestListener = function (req, res) { | |
if (req.url == "/getNumber") { | |
res.setHeader("Content-Type", "application/json"); | |
res.writeHead(200); | |
// This sends the magic number back | |
res.end(JSON.stringify({"value": magic_number})); | |
} else { | |
// This loads the main page | |
res.writeHead(200); | |
fs.createReadStream("index.html").pipe(res); | |
} | |
}; | |
const server = http.createServer(requestListener); | |
server.listen(port, () => { | |
console.log(`Server is running on http://localhost:${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment