- In ExpressJS, you can handle form data by using the
body-parser
middleware module. - The
body-parser
module can extract data from an HTTP request and make it available in thereq.body
property of the request object.
Below is an example of a simple ExpressJS application that allows the user to submit a form to add a car to a list of cars:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const express = require('express') const bodyParser = require('body-parser') const app = express() app.use(bodyParser.urlencoded({ extended: false })) const cars = [] app.get('/cars', (req, res) => { res.render('cars', { cars: cars }) }) app.post('/cars', (req, res) => { cars.push({ make: req.body.make, model: req.body.model }) res.redirect('/cars') }) app.listen(3000, () => { console.log('Example app listening on port 3000!') }) |
In this example, the bodyParser.urlencoded({ extended: false })
method is used to configure the body-parser
middleware module to parse URL-encoded data from the request body. The app.post('/cars', ...)
route is used to handle a POST request to the /cars
endpoint and add the new car to the cars
array. The res.redirect('/cars')
method is used to redirect the user back to the /cars
endpoint to see the updated list of cars.
Here’s an example of a Pug template that can be used to render a form for adding a car:
1 2 3 4 5 6 7 8 9 |
form(action='/cars', method='post') label(for='make') Make: input#make(type='text', name='make') label(for='model') Model: input#model(type='text', name='model') button(type='submit') Add car |
In this example, the Pug template uses a form
tag to create a form with two input fields for the make and model of the car and a submit button. The action
attribute of the form
tag is set to /cars
to specify the endpoint that the form should submit to, and the method
attribute is set to post
to specify that the form should be submitted using the POST method. The input
tags use the name
attribute to specify the names of the input fields, which will be used to extract the form data from the request body in the ExpressJS application.
You can render this Pug template by using the res.render('cars-form')
method in the ExpressJS application. You can also render the list of cars by using a Pug template that iterates over the cars
array and displays each car as a list item.