Processing forms in Express

How to use Express to process forms

This is an example of an HTML form:

<form method="POST" action="/submit-form">
  <input type="text" name="username" />
  <input type="submit" />

When the user presses the "Submit" button, the browser will automatically create aPOSTClaim/submit-formThe URL on the same source of the page. The browser sends the included data, encoded asapplication/x-www-form-urlencoded. In this particular example, the form data containsusernameEnter the field value.

The form can also be usedGETMethod, but most of the forms you will build will usePOST.

The form data will be sent in the body of the POST request.

To extract it, you will need to useexpress.urlencoded()Middleware:

const express = require('express')
const app = express()

app.use(express.urlencoded({ extended: true }))

Now you need to create aPOSTEndpoint/submit-formRoute, and any data will be inRequest.body:'/submit-form', (req, res) => {
  const username = req.body.username

Before using the data, please do not forget to verify the data, please useexpress-validator.

Download mine for freeExpress.js manual

More crash tutorials: