17

I'm a rookie in web languages so please do excuse me if my question is foolish. Basically I'm trying pass data from html-form to node.js server but even after searching a lot in google I couldn't get any relevant examples. So, can anyone please help me to learn this thing ?

The following example I found for parsing data to php script so how can I tweak this code to pass data to node.js script.

Code:

<!DOCTYPE html>
<html>
<body>

<form action="/action.php" method="get" target="_blank">
 First name: <input type="text" name="fname"><br>
 Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
 </form>

<p>Click on the submit button, and the input will be sent to a page on the server called "/action_page.php".</p>

2
  • What server-side code have you written so far? Commented Oct 6, 2018 at 2:47
  • The above code is client-side. It will communicate with a piece of code on a different computer called server software which is running on, a server. Node.JS allows quick creation of http(s) servers where as php is generally executed as part of the apache web server as a dynamic scripting element of the overall server. To summerise, you will be looking to find a node.js http server example. Commented Oct 6, 2018 at 2:54

2 Answers 2

28

I would highly suggest using a framework like Express for a more pleasant Node.js interactions. So the first thing you would have to do is install it:

npm install express

And for my example, I'll install an additional middleware, called body-parser.

npm install body-parser  // this allows us to access req.body.whatever

After that make a simple server to handle your POST requests, like this:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({ extended: true })); 

app.post('/example', (req, res) => {
  res.send(`Full name is:${req.body.fname} ${req.body.lname}.`);
});

const port = 8080;

app.listen(port, () => {
  console.log(`Server running on port${port}`);
});

And here is our HTML form: So we're sending our data to our localhost [http:// 127.0.0.1], port 8080 and a route of /example --> All that was configurated in our little Express server

<form action="http://localhost:8080/example" method="POST">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
 <button type="submit">Send to backend</button>
</form>
Sign up to request clarification or add additional context in comments.

5 Comments

imho it is very good. I love express and I think that what you wrote should work too - that's why upvote from me
thanks a lot for your great answer sir but could you please tell me what's the use of body-parser
body-parser used to be a part of the Express framework, but since the v4 it has been deprecated, and now its available as a separate NPM package. It's just like it sounds, a Node.js body parsing middleware. The message body (if any) of an HTTP message is used to carry the payload body of that request/ response. So the req.body holds parameters that are sent up from the client as part of a POSTrequest. And by using it you're able to access its properties (e.g. fname via req.body.fname). It does just that, it parses the request's body and allows you to get the needed data.
body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body. This body-parser module parses the JSON, buffer, string, and/ or URL encoded data submitted using HTTP POST request. I hope that made sense?! :) For future reference just visit their docs.
Hi @Bigga_HD Thank you so much for your response. But I keep getting 'Undefined' for every parameter I sent. Can you kindly see and let me know why? Thanks in advance
8

You've got a couple of different ways to solve your problem here.

Here's the simplest:

You can use the HTML form directly like you've shown in your example. But you need to understand what it's doing under the hood. So I'll give you a quick explanation.

Here's the bare bones HTML file that you need to write:

<!DOCTYPE html>
<html>
  <body>
    <form action="/your-node-server-route-name" method="POST">
     <input name="give-me-a-name" type="text" />
     <button type="submit">Send This Bad Boy To The Server</button>
    </form>
  </body>
</html>

So here's what's going on.

In the form tag the action defines where you want to send the data you collect from your user. This is the URL of the route you set up for handling this data on your node server (NOTE: this could be any server, not just node). So if you have a server running at http://localhost:3000 and your route for handling this data is /handle-form-data, then you would write your action as action="http://localhost:3000/handle-form-data" just like that. If your node server also serves this HTML page, then you can use a relative path to point to your route like this: action="/handle-form-data".

The method defined what HTTP method you want to use when submitting your form. For sending data you want to use the POST method. So we write method="POST" to let the node server know we are making a post request. If you are using Express as your web server framework, then you need to configure your route to handle post requests like so:

app.post("/handle-form-data", (req, res) => {
  // Do Something in Node here
})

The input tag nested inside the form is used to collect user input. You have to assign a name property to your data so that you can recognize this piece of data on the server. You can give it any name you like. So, for instance, if you want to collect a user's birthday, then write name="user-birthday". The type="text" just tells the browser to render a certain type of style.

Finally, the button tag will allow the user to send the form to your server. Give the button a type="submit" to tell the browser that when a user clicks the button, that the form should be sent.

...............................................

And that's it! That's the basics of handling forms.

But be aware that there are a lot of drawbacks to this simple approach that you may want to take care of in the future. For that I recommend looking at the fetch() method used in Javascript, or using a library like Axios. They will make your life a whole lot easier

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.