So, I started learning node.js recently from the official documentation and couldn't find a way to get form data submitted from the frontend. I went through the http module up to the http.request() method where I learnt how to fetch data from an API using the .on("data") method. I tried it on my http server and it worked even though it was not totally but then , it was a relief. I kept studying the docs until I stumbled upon a module called "querystring". So, we will be using the querystring module in node.js to parse client POST data. You can check it out in the office doc or continue reading.
Going forward, well create a simple form in html to send our post data to the backend.
Create form.html
<!-- form.html -->
<!doctype html>
<html>
<head>
<title>Send post data to node.js</title>
</head>
<body>
<form method="post">
<input type="name" name="name" placeholder="Name" /><br />
<input type="password" name="password" placeholder="Password" /><br />
<button>Submit</button>
</form>
</body>
</html>
That will be all for our html form. Next, we'll take care of our backend.
Create server.js
// server.js
const http = require("http");
const fs = require("fs");
const querystring = require("querystring");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, {
"content-type": "text/html"
})
fs.readFile("form.html", "utf8", (err, html) => {
res.end(html);
})
if (req.method === "POST") {
let data = "";
req.on("data", (chunk) => {
data += chunk;
})
req.on("end", () => {
const parsedString = querystring.parse(data);
console.log(parsedString);
})
}
}
})
server.listen(3000, () => {
console.log("Listening");
})
Let's break it down.
- We use the req.on("data") to get the post data in chunks. We then append the chunk data to our data variable.
- We use the req.on("end") to check when the data is completed. The returned data looks like this -> "name=codewitgabi&password=12345";
- We use the querystring.parse() method to clean/parse the data into a JavaScript object.
You can destructure the data using object destructuring to get the name and password.
Congratulations, you just learnt how to parse post data in node.js. See the full code here
Top comments (0)