2 ways to get POST body data in Express with Examples | GoLinuxCloud
Advertisement
You can get POST body data using express.json()
or express.urlencoded()
to support JSON and URL-encoded bodies, respectively.
// express.json()
app.use(express.json([options]))
// express.urlencoded()
app.use(express.urlencoded([options]))
This tutorial simplifies handling express.js post params by briefly explaining the technologies involved and then taking you through practical examples.
It would be helpful to have basic Node.js and Express.js knowledge. Read on to learn more.
Nội Dung Chính
How express communicates with the client
Simply put, express is a cluster of middleware. Middleware is a function that intercepts requests and responses to control resource transfer.
Express classifies middleware depending on the role and assigns them varying parameters. Routes are mini-servers that mainly handle HTTP verbs: POST, GET, DELETE, PUT, and PATCH. They receive two parameters: request
and response
objects.
Custom middleware receives request
, response
, and next
objects. Error handlers receive four parameters: error
, request
, response
and next
objects.
The request data gets attached to the request object. For example, express attaches form data to the request body’s property.
const formData = req.body
Likewise, the server attaches responses to the response object as JSON or renders them to a view
when using a templating engine like ejs
.
Advertisement
Express mainly receives data in JSON or via URL in encoded format. JSON is the most preferred way to transfer massive data quickly and securely. Besides, you can transfer JSON data through multiple methods like the fetch API.
Encoding URL converts unsafe, reserved, and non-ASCII characters to a universally-accepted format for easy transfer. Each character turns into bytes represented by two hexadecimal digits preceded by an escape character (%
).
Express has built-in functions to ensure data is received and is visible throughout the server. For example, the routes are attached to the use()
function to be used across the application.
Express form data is received with functions linked to various methods. For example, it handles JSON data using json()
method and URL-encoded data with urlencoded()
method.
The methods enable you to control the data limit or choose to send data using the qs library (extended: true
) or as a queryString library (extended: false
).
Now that you know what goes on during express.js POST data handling, it would be best to see how to do it practically.
How to get POST body using express.json() method
This section shows you how to handle JSON data with express.json()
and fetch API. Get the complete code through this GitHub repository URL before diving into the code explanation.
Here is the explanation of the folder structure.
Public
The public folder contains the static files: index.html
, style.css
, and frontend.js
.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="frontend.js" defer></script>
<title>User registration</title>
</head>
<body>
<main>
<h2>Register</h2>
<form>
<div>
<input type="text" name="username" id="username" placeholder="Username" required>
</div>
<div>
<input type="email" name="email" id="email" placeholder="Email" required>
</div>
<button>Send</button>
</form>
<h2>Latest User</h2>
<div>
<ul>
<li>None</li>
</ul>
</div>
</main>
</body>
</html>
The form sends a username and an email to an express server through the fetch API implemented in the frontend.js
file.
frontend.js
document.querySelector('button').addEventListener('click', (e) => {
e.preventDefault()
const username = document.getElementById('username').value
const email = document.getElementById('email').value
const li = document.querySelector('li')
const data = {username, email}
const handleFormData = async () => {
const sent = await fetch('/registration', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
try {
const response = await sent.json()
li.textContent = `${response.username} => ${response.email}`
} catch (error) {
console.log(error)
}
}
handleFormData()
})
On clicking the button, the handleFormData()
function bundles the username and email into the data
object and sends it to the server implemented in the index.js
file.
index.js
import express from 'express'
const app = express()
// read static files
app.use(express.static('public'))
// receive post body data from index.html in the public folder
app.use(express.json({extended: true, limit: '1mb'}))
// api endpoint
app.post('/registration', (req, res) => {
const { username, email } = req.body
console.log(req.body)
// resend json data
res.status(200).json({ username, email })
})
app.listen(3000)
The server accepts a maximum size of 1 MB of JSON data through the express.json()
method. On clicking the frontend button, the data is received through the /registration
endpoint. We print the POST body, dissect the username and email, then return them to the frontend as JSON data.
The fetch API receives the object in a try-catch block.
try
{
const response = await sent.json()
li.textContent = `${response.username} => ${response.email}`
}
catch (error)
{
console.log(error)
}
The try block decodes the data and appends it to the li
element.
Output:
The data sent through the form gets printed on the (backend) terminal. Likewise, the same data sent through the server as JSON gets painted to the DOM.
How to get POST body using express.urlencoded() method
The most familiar way to get POST body server-side is to use the urlencoded()
method and a templating engine like ejs
. And this section shows you just that. You can also get the code on GitHub before diving into the code explanation.
package.json
{
"name": "ejsurlencoded",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.8",
"express": "^4.18.1",
"express-ejs-layouts": "^2.5.1"
}
}
We install the web server express
, a tool to restart the server nodemon
, the templating engine ejs
, and its layouts express-ejs-layouts
. We then import the modules into the index.js
file.
index.js
import express from 'express'
import expressEjsLayouts from 'express-ejs-layouts'
const app = express()
let user = null;
//configure ejs
app.set('view engine', 'ejs')
app.use(expressEjsLayouts)
// read static files
app.use(express.static('public'))
// receive post body data
app.use(express.urlencoded({extended: true, limit: '1mb'}))
// home route
app.get('/', (req, res) => res.render('index', { user }))
// send form data to the api endpoint
app.post('/registration', (req, res) => {
user = req.body
console.log(user)
// redirect to the home page after resetting the user object with the form data
res.redirect('/')
})
app.listen(3000)
We configure the templating engine to interact with the frontend in the views
folder. The views/index.ejs
file sends form data to the /registration
endpoint.
We reassign the user
object with the POST body’s data received through the express.urlencoded()
method and redirect the user to the home page.
Summary
express.json()
and express.urlencoded()
are the recommended methods to get POST body. It would be best to understand how express receives and sends form data to apply the methods effectively.
Related Keywords: express text, express post body, express get post data, express post params, post expres, express js post parameters, express get post body, express js post params, how to get post data in express js, node express post data