0

I know it's possible to get data sent by the user in the back-end using Express.js which is:

router.get("/pathName", async function(req, res){
  count = req.body;
})

But how to do this in vanilla (pure) Node.js itself?

Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33
  • 1
    https://nodejs.dev/learn/get-http-request-body-data-using-nodejs – Barmar May 21 '22 at 00:33
  • 2
    Why? What are you trying to do that makes "using express" (or any other established web server framework) not an option? Node might have http/https APIs available, but they're _just_ the http/https parts, and writing a web server on top of those is neither trivial, nor smart. – Mike 'Pomax' Kamermans May 21 '22 at 00:33
  • I am just a beginner, and I wanna learn Node Js for it to be easy to master other node frameworks. That's why I try to build some simple projects in Node Js –  May 21 '22 at 00:38
  • 1
    Does this answer your question? [How is an HTTP POST request made in node.js?](https://stackoverflow.com/questions/6158933/how-is-an-http-post-request-made-in-node-js) – ricxk May 21 '22 at 00:39
  • express is just a js library go look at the source code to see how they do it. – Jared Smith May 21 '22 at 01:02

1 Answers1

1

Here's an example of a simple server.

const http = require('http');

http
  .createServer((req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/html',
    });
    switch (req.url) {
      // http://localhost:8080/
      case '/':
        res.write('<h1>Home</h1>');
        break;
      // http://localhost:8080/page
      case '/page':
        res.write('<h1>Page</h1>');
        break;
    }
    res.end();
  })
  .listen(8080);

Also, here's an example (probably incomplete in terms of all edge cases...) of getting JSON data from a request payload:

const http = require("http");

// server that only supports POST /count
// expects JSON data to be passed like { "count": 100 }
// must have application/json content type header and POST method

http
  .createServer(async (req, res) => {
    // ensure method is content type json, POST, and /count
    if (
      req.headers["content-type"] != "application/json" ||
      req.url !== "/count" ||
      req.method !== "POST"
    ) {
      res.writeHead(404, {
        "Content-Type": "application/json",
      });
      res.write(JSON.stringify({ message: "Unsupported route" }));
      res.end();
    }

    // try to read body
    let body;
    try {
      body = await readBody(req);
    } catch (err) {
      res.writeHead(400, {
        "Content-Type": "application/json",
      });
      res.write(JSON.stringify({ message: err.message }));
      res.end();
    }

    // try to parse body
    let parsedBody;
    try {
      parsedBody = JSON.parse(body);
    } catch (err) {
      res.writeHead(400, {
        "Content-Type": "application/json",
      });
      res.write(JSON.stringify({ message: err.message }));
      res.end();
    }

    // make sure count property is present in parsed body
    if (typeof parsedBody.count === "undefined") {
      res.writeHead(400, {
        "Content-Type": "application/json",
      });
      res.write(JSON.stringify({ message: err.message }));
      res.end();
    }

    // create response
    res.writeHead(200, {
      "Content-Type": "application/json",
    });
    res.write(JSON.stringify({ message: "Got " + parsedBody.count }));
    res.end();
  })
  .listen(8080);

function readBody(req) {
  return new Promise((res, rej) => {
    let body = "";
    req.on("data", (data) => {
      body += data;
    });
    req.on("end", () => {
      res(body);
    });
    req.on("error", (err) => {
      rej(err);
    });
  });
}

Cool to see how it works for learning. But if you're using it for a project, I'd highly recommend Express or another framework/lib as you'll find it will get quite painful to try to consider all various cases you will need. Frameworks like Express are quite light anyway.

Talha
  • 807
  • 9
  • 13