expressjsHow do I use Express.js to read the body of a request?
Express.js is a web application framework for Node.js that allows you to create web applications. One of the things you can do with Express.js is read the body of a request. To do this, you need to use the body-parser
middleware. Here is an example of how to use it:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/', (req, res) => {
console.log(req.body)
})
This example sets up the body-parser
middleware to parse both application/x-www-form-urlencoded
and application/json
data. Then, when a POST
request is made to /
, the body of the request is printed to the console.
The body-parser
middleware can also be used to read data from PUT
and DELETE
requests.
Code explanation
const express = require('express')
: This line imports the Express.js module.const bodyParser = require('body-parser')
: This line imports thebody-parser
middleware.app.use(bodyParser.urlencoded({ extended: false }))
: This line sets up thebody-parser
middleware to parseapplication/x-www-form-urlencoded
data.app.use(bodyParser.json())
: This line sets up thebody-parser
middleware to parseapplication/json
data.app.post('/', (req, res) => { console.log(req.body) })
: This line sets up aPOST
route that will print the body of the request to the console.
Helpful links
More of Expressjs
- How do I set the time zone in Express.js?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js and Vite together for software development?
- How can I set up auto reloading in Express.js?
- How do I download a zip file using Express.js?
- How can I use Express.js to yield results?
- How do I use Zod with Express.js?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js and Winston together to create a logging system?
- How can I use Express.js to make an XHR request?
See more codes...