How to handle forms using ExpressJS
Prerequisites
In order to handle forms in ExpressJS, you must first have a basic understanding of ExpressJS. You can learn basic ExpressJS here.
Step 1: Setup app
Before you are able to create or handle forms, you must setup your app. You can do so with this NodeJS code:
const express = require("express");
const app = express();
app.use(express.static("./public"));
app.use(express.urlencoded({ extended: true }));
// ...
app.listen(1010, () => {
console.log("Server started");
});
If you don’t understand what this code does, go here.
Next, you must create the public
directory. Create a folder named public
, and in it, create a file named index.html
.
In index.html
, type !, which is an Emmet abbreviation, and press Tab to activate the abbreviation. Your boilerplate HTML code should instantly appear.
Step 2: Creating the HTML form
In the <body>
tag of index.html
, you will write the code for the form.
Example form:
<form method="post">
<label for="input">Type anything you want below</label><br/>
<input name="input"/>
<button type="submit">Submit Form</button>
</form>
<form method="post">
creates the form, specifying that it should be submitted using the POST HTTP method.
<label for="input">
creates a label element in the form specifying what the user should enter in the input element below. It is recommended to have a <label>
element for every user input element in the form. Each <label>
element should have a for
attribute that specifies the name
of the element it is for.
<input name="input" />
creates an input element in the form where the user will enter data. A name
element is required for every user input element in the form that you want to submit. If a form element does not have a name
attribute, it will not be submitted to the server when a user submits the form.
<button type="submit">
creates a submit button that, when pressed, will submit the form and send the data to the server for processing.
Step 3: Processing the form
Then, when a user clicks the Submit Form button, the data will be sent to the server. In index.js
, we need code to process it.
Use the following Node.js code:
app.post('/', () => {
let data = req.body.input; // Use `req.body.<name attribute>` to access an element in the form
res.send(data); // Send what the user typed
});
That’s it!
From here, you can do more advanced things, such as save the user input to a database, but that’s it for now.