res.json()
or res.send()
.Example:
const user = { id: 1, name: "Vivek" };
res.json(user); // Serializes 'user' object to JSON format and sends it
express.json()
middleware.Example:
app.use(express.json()); // Parses incoming JSON requests into JS objects
app.post("/user", (req, res) => {
const userData = req.body; // Deserialized data
console.log(userData);
res.send("User received");
});
const express = require("express");
const app = express();
app.use(express.json()); // Deserializes incoming JSON
app.post("/user", (req, res) => {
// Deserialized object
const user = req.body;
// Serialize and send it back
res.json({
message: "Received user data",
user: user
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
express.urlencoded()
]express.urlencoded()
is a built-in middleware function in Express.js used to parse incoming requests with URL-encoded payloads — typically from HTML form submissions.
When a form is submitted using:
<form method="POST" action="/submit">
<input type="text" name="username" />
<button type="submit">Submit</button>
</form>