Created
January 7, 2022 09:19
-
-
Save jpdias/bc1569741b019a3ee5e45ebe75144439 to your computer and use it in GitHub Desktop.
Basic HTTP server
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
const http = require('http'); | |
// Create a local server to receive data from | |
const server = http.createServer((req, res) => { | |
console.log(req.url) | |
console.log(req.method) | |
res.writeHead(200, { 'Content-Type': 'application/json' }); | |
if (req.method === "GET" && req.url == "/test") { | |
res.end(JSON.stringify({ | |
data: 'Hello World!' | |
})); | |
} | |
if (req.method === "POST" && req.url == "/test") { | |
let body = []; | |
req.on('data', (chunk) => { | |
console.log(chunk) | |
body.push(chunk); | |
body = Buffer.concat(body).toString() | |
console.log(JSON.parse(body)) | |
}) | |
res.end(JSON.stringify({ | |
data: 'Hello World!' | |
})); | |
} | |
}); | |
server.listen(8000); | |
// https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/ | |
// https://nodejs.org/api/http.html#httpcreateserveroptions-requestlistener |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment