Categories
Express JavaScript Answers

How to Access POST Form Field Values with Express?

Spread the love

To access POST form fields values with Express, we can use the body-parser middleware to parse the POST form fields into a JavaScript object.

To install the package, we run:

npm install --save body-parser

Then we can write:

const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.post('/', (req, res) => {
  res.json(req.body)
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to add body-parser into our app with:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

Now we can parse JSON or URL encoded request data into the req.body property.

Therefore, when we send request data into the POST / route, we see the request value returned as the response in an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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