5 ways to make HTTP requests in Node.js - LogRocket Blog
Sat Apr 20 2024 13:17:46 GMT+0000 (Coordinated Universal Time)
Saved by
@USFAkbari
#javascript
const http = require("http");
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="/submit-form" enctype="application/x-www-form-urlencoded" method="POST">
<label> Enter Name:
<input type="text" autocomplete="name" name="name" required />
</label>
<input type="submit" />
</form>
</body>
</html>
`;
const server = http.createServer((req, res) => {
switch (req.method) {
case "GET":
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(html);
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page not found");
}
break;
case "POST":
if (req.url === "/submit-form") {
let body = "";
req.on("data", (data) => {
body += data;
});
req.on("end", () => {
console.log("Request body: " + body);
// Parse, validate, and sanitize
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ body }));
});
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page not found");
}
break;
default:
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Method not supported");
}
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Your app is listening on PORT ${PORT}`);
});
content_copyCOPY
https://blog.logrocket.com/5-ways-make-http-requests-node-js/
Comments