Categories
Express JavaScript Answers

How to Accept form-data Request Data with Express?

Spread the love

To accept form-data request data in our Express app, we can use the body-parser package.

To install it, we run:

npm i body-parser

Then we can use it by writing:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000

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

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

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

so that we can accept form-data requests in our Express app.

We call bodyParser.urlencoded to accept form-data requests.

The extended option lets us choose between parsing the URL-encoded data with the querystring library with its set to false or the qs library when it’s set to true .

Therefore, when we make a x-www-form-urlencoded request with some key-value pairs, we should get them in the req.body object.

So we’ll see them returned as the response when we make a POST request to the / route.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.