How To Send Data From A Form Using Express?

How To Send Data From A Form Using Express?

·

2 min read

In this post, I will show you how to send data from a form using express.js. Sending data with express is very easy. In short, to get the data that has been sent over to another page(e.g. a controller), we use req.body.theInputName, where theInputName is equal to whatever the value of the input’s name was.

A Contrast with PHP If you know PHP, I think you will instantly understand what is going when you see a comparison with the same thing in PHP.

PHP Code

form.php
<form action="test.php" method="POST">
<input name="abc">
<input type="submit" value="submit"/>
</form>

PHP Code

test.php
<?php
echo $_POST["abc"];
?>

So this is our form if we were sending data using PHP.

You can see that we are sending the data value using the POST method and that the input name is abc. And to get that value, we are using $_POST["abc"].

The place we are sending the data (the address) is the value of the "action" attribute. And once we send that data over to test.php, we want to output that data there; this is what we end up with if we did everything correctly.

The Same Code But With Node.js Let's instead now write code to do the exact same thing but this time, we're going to be writing in Express.

So this is the HTML file if we are now writing using express.

Express.js Code

<form action=“/test” method=“”>
<input name="abc" >
<input type=“submit” value=“submit”>
</form>

Our code will send data to the "test" route, and the test route can be located in our routes/index.js file

Once we get there, we do this:

Code

router.post('/test', function(req, res, next){
res.send(req.body.abc);
}

So we just wrote more or less the same code but, instead, we wrote it using Express. And in Express, instead of a page name, we specify a route address in that "action" attribute.

If done correctly, the result is the same. Once we get to the action's route ("/"), we use res.send() to display out the value of the req.body.abc that we were sent.

And if we did everything right, we should see something like this.

Screen Shot 2022-10-05 at 3.04.24 PM.png