PASSWORD RESET

Your destination for complete Tech news

How to access post form fields in Node JS express?

301 0
< 1 min read

To access form fields in an HTTP POST request in an Express.js app, you can use the body-parser middleware. The body-parser middleware parses the request body and populates the request.body object with the parsed data.

Here’s an example of how to use the body-parser middleware to access form fields in an HTTP POST request:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// Use the body-parser middleware
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/form', (request, response) => {
  // Access form fields
  const name = request.body.name;
  const email = request.body.email;

  // Do something with the form fields
  console.log(`Name: ${name}`);
  console.log(`Email: ${email}`);

  response.send('Form received');
});

In this example, we use the app.use() function to apply the body-parser middleware to all routes in the app. Then, we define a route for the POST /form endpoint, which receives a request and a response object as arguments. Inside the route handler, we access the name and email form fields using the request.body object.

Note: The body-parser middleware is designed to parse the request body of an HTTP POST request. If you are using a different HTTP method, such as GET or PUT, you will need to use a different method for accessing the form fields.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.