In this post I am going to show how to create a simple HTTP Server based on Node.js that accepts Post requests from a source.
The idea is to enter some data in the above form and the form sends the data to the Node.js server as post parameters.
My Node.js server:
The above code creates a HTTP Server that accepts Post requests from a source.
Once I entered the data in the form and submitted, I got here:
Request:
Response:
As you can see in the above image the post method doesn't send any parameters in the query string.
In the Node.js server code, I have written a console.log for every parameter we get from post. Let us see what node.js REPL has to show.
In the code, I have written a split in javascript and separated the variables from the query string post sends to the server and not to the browser.
This is just a simple demonstration of how Node.js accepts Post requests.
Please don't hesitate to suggest ☺, Happy learning.
I am taking the following to demonstrate:
A HTML Form with method="post"
A Node.js HTTP Server that accepts post requests from the form.
My HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <html> <body> <form action="http://localhost:2000/somePage" method="post"> <table align="center" style="font-size:20px;"> <tr> <td>Username: </td> <td><input type="text" name="userName"/></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="pwd"/></td> </tr> <tr> <td>Date of birth: </td> <td><input type="date" name="name4Date"/></td> </tr> <tr> <td colspan="2"><input type="submit"/></td> </tr> </table> </form> </body> </html> |
The idea is to enter some data in the above form and the form sends the data to the Node.js server as post parameters.
My Node.js server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var http = require("http"); http.createServer(function(request, response) { request.on("data", function(dataFromPost) { var data = ""; data+=dataFromPost; var splitVar = data.split("&"); for(var i = 0;i < splitVar.length;i++) { console.log(splitVar[i]); } }); request.on("end", function() { response.writeHead(200); response.write("<p style='color:red;font-size:30px;text-align:center;'>"+ "A Node.js Server that accepts post requests</p>"); response.end(); }); }).listen(2000); console.log("Server started successfully"); |
The above code creates a HTTP Server that accepts Post requests from a source.
Once I entered the data in the form and submitted, I got here:
Request:
Response:
As you can see in the above image the post method doesn't send any parameters in the query string.
In the Node.js server code, I have written a console.log for every parameter we get from post. Let us see what node.js REPL has to show.
In the code, I have written a split in javascript and separated the variables from the query string post sends to the server and not to the browser.
This is just a simple demonstration of how Node.js accepts Post requests.
Please don't hesitate to suggest ☺, Happy learning.