ExpressJS Form

  • 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 the req.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:

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:

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top