Categories
JavaScript Answers

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

Spread the love

To create Node.js server that accepts POST requests, we 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);

to call createServer with a callback that checks the request method with the request.method property.

If it’s 'POST', then a post request is received.

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 *