1703942684

Handling HTTP POST requests with node.js


For those learning Nodejs, here is a tutorial on how to handle HTTP POST requests. The HTTP POST method is used to send data to the server, as opposed to the HTTP GET method, which is used to obtain data. To be able to receive POST data, we need to instruct our server how to accept and handle POST requests. A POST request typically contains data within the body of the request, which is sent to the server to be handled. The submission of a web form is typically done via an HTTP POST request. 1. Start by creating a directory for this recipe. Well also need a file named server.js that will contain our HTTP server: #### $ mkdir post-server #### $ cd post-server #### $ touch server.js 2. We also need a to create a subdirectory called public, containing a file named form.html that will contain an HTML form: #### $ mkdir public #### touch #### public/form.html 1. First, lets set up an HTML form with input fields for forename and surname. Open form.html and add the following: ```html <form method="POST"> <label for="forename">Forename:</label> <input id="forename"> <label for="surname">Surname: </label> <input id="surname" name="surname"> <input type="submit" value="Submit"> </form> ``` 2. Next, open the server.js file and import the fs, http, and path Node.js core modules: ```js const http = request("http"); const fs = require("fs"); const path = require("path"); ``` 3. On the next line, well create a reference to our form.html file: ```js const form = fs.readFileSync(path.join(__dirname, "public", "form.html")); ``` 4. Now, add the following lines of code to server.js to set up the server. Well also create a function to return the form named get() and an error function named **error():** ```js http .createServer((req, res) => { if(req.method === "GET") { get(res); return; } error(405, res); }) .listen(3000); function get(res) { res.writeHead(200, {"Content-Type": "text/html", }); res.end(form); } function error(code, res) { res.statusCode = code; res.end(http.STATUS_CODE[code]) } ``` 5. Start your server and confirm that you can view the form in your browser at http://localhost:3000: $ node server.js If you liked this post and want to talk to me more about Nodejs, send me a message in this room [https://chat-to.dev/chat?q=world-nodejs](https://chat-to.dev/chat?q=world-nodejs) and Ill be there to answer you.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2024 © Chat-to.dev]