node.jsposthttpmodule

Retrieve JSON from HTTP Post - Node JS


I'm trying to get the JSON from a POST request from Postman, however I'm getting no access to the info and just get a route not found. I know the endpoint is fine as the get request are working just fine. I'm trying to complete the request with no frameworks as express. Thanks for any idea.

  const server = http.createServer(async (req, res) => {
          res.statusCode = 200;
    
        // Crete an autor
  } else if (req.url === '/api/authors' && req.method === 'POST') {
        const server = http.createServer((req, res) => {
          req.on('data', (chunk) => {
            console.log(`Data chunk available: ${chunk}`);
          });
          req.on('end', () => {});
        });
      } else {
        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: 'Route Not Found' }));
      }

Solution

  • Your code structure is incorrect, please see below link to learn how handle post method:

    https://www.pabbly.com/tutorials/node-js-http-server-handling-get-and-post-request/