How to use Express In NodeJS
Express.js simplifies the process of handling HTTP requests, including POST requests. Let’s dive into a practical example of handling POST data with Express.js:
Approach
- The
index.html
file includes a form with two inputs for username and password. - When the form is submitted, a POST request is sent to the home route (“/”) of the server.
- The request body contains the username and password, and the header includes an authorization token.
- The server handles the POST request using the
app.post()
method. - The server responds by sending back the username, password, and authorization token.
- These details are printed to the console for further examination.
Example: Implementation to show how to get POST data in nodejs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>POST DEMO</title>
</head>
<body>
<form>
<div>
<label>Username</label>
<input type="text" id="user" />
</div>
<div>
<label>Password</label>
<input type="password"
id="pass" />
</div>
<button type="submit">
Submit
</button>
</form>
<script>
document.querySelector('button')
.addEventListener('click', (e) => {
e.preventDefault();
const username = document
.querySelector('#user').value;
const password = document
.querySelector('#pass').value;
fetch('/', {
method: 'POST',
headers: {
Authorization: 'Bearer abcdxyz',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username,
password,
}),
})
.then((res) => {
return res.json();
})
.then((data) => console.log(data));
});
</script>
</body>
</html>
// Importing express module
const express = require('express');
const app = express();
app.use(express.json());
app.get('/',
(req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/',
(req, res) => {
const { username, password } = req.body;
const { authorization } = req.headers;
res.send(
{
username,
password,
authorization,
});
});
app.listen(3000,
() => {
console.log(
'Our express server is up on port 3000'
);
});
Steps to run the Application
node app.js
Output: Open the browser and go to http://localhost:3000 and you will see the following output.
How to Get POST Data in Node ?
Handling POST data is a fundamental aspect of developing web applications and APIs using Node.js. POST requests are used when a client needs to send data to the server, such as submitting form data, uploading files, or sending JSON payloads. This article will cover various methods to retrieve and handle POST data in Node.js, enhancing your server-side capabilities.