Sometimes, we want to create a Node.js server that accepts POST requests with JavaScript.
In this article, we’ll look at how to create a Node.js server that accepts POST requests with JavaScript.
How to create a Node.js server that accepts POST requests with JavaScript?
To create a Node.js server that accepts POST requests with JavaScript, we check the request.method
property.
For instance, we write
const http = require("http");
const server = http.createServer((request, response) => {
response.writeHead(200, { "Content-Type": "text/plain" });
if (request.method === "GET") {
response.end("received GET request.");
} else if (request.method === "POST") {
response.end("received POST request.");
} else {
response.end("Undefined request .");
}
});
server.listen(8000);
console.log("Server running on port 8000");
to call createServer
with a callback that’s called when a request is received.
If request.method
is 'POST'
, then a post request is received.
Conclusion
To create a Node.js server that accepts POST requests with JavaScript, we check the request.method
property.