Categories
JavaScript Answers

How to create a Node.js server that accepts POST requests?

Spread the love

Sometimes, we want to create a Node.js server that accepts POST requests.

In this article, we’ll look at how to create a Node.js server that accepts POST requests.

How to create a Node.js server that accepts POST requests?

To create a Node.js server that accepts POST requests, we can use the http module.

For instance, we write

const http = require("http");
const server = http.createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "textplain" });
  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 http.createServer with a callback to create a web server.

We call it with a callback that receives the request.

If request.method is 'POST', then a POST request is received.

And then we call response.end to return a response body string.

Conclusion

To create a Node.js server that accepts POST requests, we can use the http module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *