Skip to content

Instantly share code, notes, and snippets.

@jpdias
Created January 7, 2022 09:19
Show Gist options
  • Save jpdias/bc1569741b019a3ee5e45ebe75144439 to your computer and use it in GitHub Desktop.
Save jpdias/bc1569741b019a3ee5e45ebe75144439 to your computer and use it in GitHub Desktop.
Basic HTTP server
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