Introduction
In the previous article, we looked at the Express.js GET method, route parameters, and query parameters.
We learned how to retrieve data from an API:
GET /api/users
and how to retrieve a specific user:
GET /api/users/10
But what happens when we want to send data to the server?
For example, imagine a registration form:
Name: John
Email: john@example.com
Age: 25
When the user clicks Register, the frontend needs to send this information to the backend.
This is where the POST method comes in.
A typical request might look like:
POST /api/users
with data in the request body:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
In Express.js, we can access this data using:
req.body
In this article, we'll understand POST requests from the ground up and build a practical API step by step.
What Is the POST Method?
POST is an HTTP method commonly used when we want to send data to a server.
For example:
POST /api/users
could be used to create a new user.
Other examples include:
POST /api/products
POST /api/orders
POST /api/blogs
POST /api/comments
POST /api/auth/login
The basic flow looks like this:
Frontend
|
| POST request
| + request body
↓
Express Server
|
| Process data
↓
Database
|
| Save data
↓
Express Server
|
| Response
↓
Frontend
GET vs POST
It's important to understand the difference between the two.
GET
Usually used to retrieve data.
GET /api/users
Example response:
[
{
"id": 1,
"name": "John"
}
]
POST
Usually used to send data and create a new resource.
POST /api/users
Request body:
{
"name": "Jane",
"email": "jane@example.com"
}
A simple way to remember:
GET
→ Give me data
POST
→ Here is some data
What Is a Request Body?
The request body contains data sent by the client to the server.
For example:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
This data is called the request body.
The client could be:
- React application
- Next.js application
- Mobile application
- Postman
- Another backend service
- HTML form
The client sends the data:
Client
|
| Request Body
↓
Express API
Express then reads the body using:
req.body
Creating Our Express Project
Let's create a simple Express application.
mkdir express-post-api
cd express-post-api
npm init -y
npm install express
Create:
server.js
Our initial structure:
express-post-api/
│
├── node_modules/
├── package.json
├── package-lock.json
└── server.js
Step 1: Create an Express Server
Open server.js:
const express = require("express");
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Start the server:
node server.js
You should see:
Server running on http://localhost:3000
Our server is running.
Now let's create our first POST API.
Step 2: Create a POST Route
Express provides the app.post() method.
app.post("/api/users", (req, res) => {
res.json({
message: "User created successfully"
});
});
Our complete code:
const express = require("express");
const app = express();
const PORT = 3000;
app.post("/api/users", (req, res) => {
res.json({
message: "User created successfully"
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Now we have:
POST /api/users
But there is a problem.
We haven't told Express how to read JSON data from the request.
Let's fix that.
Step 3: Add express.json()
Add this before your routes:
app.use(express.json());
Our server becomes:
const express = require("express");
const app = express();
const PORT = 3000;
// Parse JSON request bodies
app.use(express.json());
app.post("/api/users", (req, res) => {
res.json({
message: "User created successfully"
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
This line is extremely important:
app.use(express.json());
It tells Express:
"When a request contains JSON data, parse it so I can access it through
req.body."
Why Do We Need express.json()?
Suppose the client sends:
{
"name": "John",
"email": "john@example.com"
}
Without JSON parsing middleware, Express won't automatically give us the parsed JavaScript object we expect in req.body.
After adding:
app.use(express.json());
we can access:
req.body
For example:
app.post("/api/users", (req, res) => {
console.log(req.body);
res.json({
message: "User created successfully"
});
});
If the client sends:
{
"name": "John",
"email": "john@example.com"
}
then:
req.body
will contain:
{
name: "John",
email: "john@example.com"
}
Step 4: Read Data from req.body
Now let's create a useful API.
app.post("/api/users", (req, res) => {
const { name, email, age } = req.body;
console.log(name);
console.log(email);
console.log(age);
res.json({
message: "User received successfully",
user: {
name,
email,
age
}
});
});
Now send:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
The response will be:
{
"message": "User received successfully",
"user": {
"name": "John",
"email": "john@example.com",
"age": 25
}
}
We've successfully received data from the client.
Understanding req.body
Let's break this down.
const { name, email, age } = req.body;
If the request body is:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
then:
name
contains:
John
email
contains:
john@example.com
and:
age
contains:
25
You can also access them directly:
req.body.name
req.body.email
req.body.age
Testing the POST API with Postman
A browser is convenient for testing GET requests, but POST requests usually require a tool such as Postman.
Create a new request:
Method:
POST
URL:
http://localhost:3000/api/users
Go to:
Body → raw → JSON
Then send:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
Click Send.
You should receive:
{
"message": "User received successfully",
"user": {
"name": "John",
"email": "john@example.com",
"age": 25
}
}
The Content-Type Header
There is one more important part when sending JSON.
The request should contain:
Content-Type: application/json
This tells the server:
"The data I'm sending is JSON."
In Postman, when you select:
Body → raw → JSON
Postman normally sets this header automatically.
A request conceptually looks like:
POST /api/users
Content-Type: application/json
{
"name": "John",
"email": "john@example.com"
}
The express.json() middleware then parses that JSON body.
POST Request Flow
Let's understand the complete process.
React / Next.js / Postman
|
|
| POST /api/users
|
| JSON Body
↓
Express Server
|
↓
express.json()
|
↓
req.body
|
↓
Route Handler
|
↓
Save / Process
|
↓
Response
This flow is fundamental to backend development.
Creating a User
Let's make our API slightly more realistic.
We'll keep users in an array for now.
const users = [];
Then:
app.post("/api/users", (req, res) => {
const { name, email, age } = req.body;
const user = {
id: users.length + 1,
name,
email,
age
};
users.push(user);
res.json({
message: "User created successfully",
user
});
});
Now when we send:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
our server creates:
{
"id": 1,
"name": "John",
"email": "john@example.com",
"age": 25
}
and stores it in memory.
Returning the Correct Status Code
Our API currently returns:
res.json(...)
Express will use a successful status code by default.
But when we create a resource, it's common to return:
201 Created
We can do that with:
res.status(201).json({
message: "User created successfully",
user
});
So our API becomes:
app.post("/api/users", (req, res) => {
const { name, email, age } = req.body;
const user = {
id: users.length + 1,
name,
email,
age
};
users.push(user);
res.status(201).json({
message: "User created successfully",
user
});
});
Response:
HTTP 201 Created
Body:
{
"message": "User created successfully",
"user": {
"id": 1,
"name": "John",
"email": "john@example.com",
"age": 25
}
}
Why Use 201 Instead of 200?
Both are successful HTTP responses, but they communicate different things.
200 OK
Usually means:
The request was successful.
201 Created
Usually means:
The request was successful and a new resource was created.
For a create API:
POST /api/users
201 Created is generally the more descriptive status code.
Adding Validation
Now we have a problem.
What happens if the client sends:
{
"name": "",
"email": "",
"age": 0
}
We shouldn't blindly accept it.
We need validation.
For example:
app.post("/api/users", (req, res) => {
const { name, email, age } = req.body;
if (!name || !email || !age) {
return res.status(400).json({
message: "Name, email and age are required"
});
}
const user = {
id: users.length + 1,
name,
email,
age
};
users.push(user);
res.status(201).json({
message: "User created successfully",
user
});
});
Now if the client sends:
{
"name": "John"
}
the server returns:
{
"message": "Name, email and age are required"
}
with:
400 Bad Request
Why Do We Need Validation?
Never assume that the frontend will always send correct data.
Even if your React application has validation, someone can directly call your API.
For example:
Postman
curl
Another application
Malicious client
So backend validation is essential.
Think of it this way:
Frontend validation
+
Backend validation
=
Safer application
Frontend validation improves the user experience.
Backend validation protects the API.
Validate the Data Type
We can also check the data types.
Suppose age should be a number.
We can write:
if (typeof age !== "number") {
return res.status(400).json({
message: "Age must be a number"
});
}
We could also validate:
if (age < 18) {
return res.status(400).json({
message: "Age must be at least 18"
});
}
For production applications, it's usually better to use a validation library such as Zod, Joi, or express-validator instead of writing large amounts of manual validation.
Handling Duplicate Email Addresses
Suppose our application doesn't allow two users to register with the same email.
We can check:
const existingUser = users.find(
(user) => user.email === email
);
if (existingUser) {
return res.status(409).json({
message: "Email already exists"
});
}
Then:
409 Conflict
can indicate that the submitted data conflicts with existing data.
A Better POST API
Let's combine everything.
app.post("/api/users", (req, res) => {
const { name, email, age } = req.body;
// Validate required fields
if (!name || !email || age === undefined) {
return res.status(400).json({
message: "Name, email and age are required"
});
}
// Validate age
if (typeof age !== "number") {
return res.status(400).json({
message: "Age must be a number"
});
}
// Check duplicate email
const existingUser = users.find(
(user) => user.email === email
);
if (existingUser) {
return res.status(409).json({
message: "Email already exists"
});
}
// Create user
const user = {
id: users.length + 1,
name,
email,
age
};
users.push(user);
// Return created user
res.status(201).json({
message: "User created successfully",
user
});
});
This is already much closer to a real API.
Sending POST Requests from JavaScript
We don't always use Postman.
A frontend application can send a POST request using fetch().
For example:
const response = await fetch(
"http://localhost:3000/api/users",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
email: "john@example.com",
age: 25
})
}
);
const data = await response.json();
console.log(data);
The important parts are:
method: "POST"
and:
headers: {
"Content-Type": "application/json"
}
and:
body: JSON.stringify({
name: "John",
email: "john@example.com",
age: 25
})
Why Do We Need JSON.stringify()?
Our JavaScript object is:
{
name: "John",
email: "john@example.com",
age: 25
}
But the HTTP request body needs to contain JSON data.
So we convert the object into a JSON string:
JSON.stringify({
name: "John",
email: "john@example.com",
age: 25
});
The result looks like:
"{\"name\":\"John\",\"email\":\"john@example.com\",\"age\":25}"
Express then parses the JSON using:
app.use(express.json());
and gives us the JavaScript object through:
req.body
So the process is:
JavaScript Object
↓
JSON.stringify()
↓
JSON Request Body
↓
HTTP Request
↓
express.json()
↓
req.body
↓
JavaScript Object
What Happens If express.json() Is Missing?
Consider:
const express = require("express");
const app = express();
app.post("/api/users", (req, res) => {
console.log(req.body);
res.json(req.body);
});
If we send JSON data, req.body may not contain the parsed object we expect.
That's why we usually configure:
app.use(express.json());
before our routes:
app.use(express.json());
app.post("/api/users", ...);
Middleware order matters.
Middleware Order Matters
This works:
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body);
});
But don't put the parser after the route:
app.post("/api/users", (req, res) => {
console.log(req.body);
});
app.use(express.json());
The request reaches the route before the JSON parser has processed it.
A good rule is:
Middleware
↓
Routes
↓
Error handling
We'll explore middleware in more detail in a separate article.
What About URL-Encoded Data?
JSON isn't the only type of request body.
HTML forms often submit data using:
application/x-www-form-urlencoded
Express provides:
app.use(express.urlencoded({ extended: true }));
For example:
const express = require("express");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Now Express can parse both JSON and URL-encoded request bodies.
JSON vs URL-Encoded Data
JSON
Content-Type: application/json
Example:
{
"name": "John",
"email": "john@example.com"
}
Parsed using:
app.use(express.json());
URL-encoded
Content-Type: application/x-www-form-urlencoded
Example:
name=John&email=john@example.com
Parsed using:
app.use(express.urlencoded({ extended: true }));
For modern frontend-to-REST-API communication, JSON is extremely common.
POST Request with Nested Data
The request body doesn't have to be flat.
For example:
{
"name": "John",
"email": "john@example.com",
"address": {
"city": "Hyderabad",
"country": "India"
}
}
Express can parse this JSON into:
req.body
Then:
const { name, email, address } = req.body;
console.log(address.city);
returns:
Hyderabad
This becomes useful when working with more complex APIs.
POST Request with Arrays
The body can also contain arrays.
For example:
{
"name": "John",
"skills": [
"JavaScript",
"React",
"Node.js"
]
}
You can access:
req.body.skills
which gives:
[
"JavaScript",
"React",
"Node.js"
]
You could then process the array or save it to a database.
Route Parameters + Request Body
POST requests can also use route parameters.
For example:
POST /api/users/10/orders
Request body:
{
"productId": 100,
"quantity": 2
}
Express:
app.post(
"/api/users/:userId/orders",
(req, res) => {
const { userId } = req.params;
const { productId, quantity } = req.body;
res.status(201).json({
userId,
productId,
quantity
});
}
);
Request:
POST /api/users/10/orders
Body:
{
"productId": 100,
"quantity": 2
}
Response:
{
"userId": "10",
"productId": 100,
"quantity": 2
}
Notice that we're using:
req.params
for the URL parameter and:
req.body
for the submitted data.
Query Parameters + Request Body
It's also technically possible to use query parameters with a POST request:
POST /api/users?sendEmail=true
Body:
{
"name": "John",
"email": "john@example.com"
}
Then:
const { sendEmail } = req.query;
const { name, email } = req.body;
However, remember that query parameters and request bodies serve different purposes.
A common design might be:
Route parameters
→ Identify the resource
Query parameters
→ Control/filter the request
Request body
→ Send the data being created/updated
Complete Express POST Example
Let's put everything together.
const express = require("express");
const app = express();
const PORT = 3000;
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Temporary in-memory database
const users = [];
// Create user
app.post("/api/users", (req, res) => {
const { name, email, age } = req.body;
// Validate required fields
if (!name || !email || age === undefined) {
return res.status(400).json({
message: "Name, email and age are required"
});
}
// Validate age
if (typeof age !== "number") {
return res.status(400).json({
message: "Age must be a number"
});
}
// Check duplicate email
const existingUser = users.find(
(user) => user.email === email
);
if (existingUser) {
return res.status(409).json({
message: "Email already exists"
});
}
// Create user
const user = {
id: users.length + 1,
name,
email,
age
};
users.push(user);
// Send response
res.status(201).json({
message: "User created successfully",
user
});
});
// Start server
app.listen(PORT, () => {
console.log(
`Server running on http://localhost:${PORT}`
);
});
Test it with:
POST http://localhost:3000/api/users
Request body:
{
"name": "John",
"email": "john@example.com",
"age": 25
}
Response:
{
"message": "User created successfully",
"user": {
"id": 1,
"name": "John",
"email": "john@example.com",
"age": 25
}
}
Common Mistakes to Avoid
1. Forgetting express.json()
Incorrect:
const app = express();
app.post("/api/users", (req, res) => {
console.log(req.body);
});
Better:
const app = express();
app.use(express.json());
app.post("/api/users", (req, res) => {
console.log(req.body);
});
2. Forgetting Content-Type
When sending JSON, make sure the request contains:
Content-Type: application/json
With fetch():
headers: {
"Content-Type": "application/json"
}
3. Forgetting JSON.stringify()
Incorrect:
body: {
name: "John"
}
Correct:
body: JSON.stringify({
name: "John"
})
4. Trusting Request Data
Don't assume:
const { name, email } = req.body;
means the data is valid.
Always validate data before processing or saving it.
5. Returning 200 for Everything
A successful response isn't always the same thing.
For resource creation:
201 Created
is generally more appropriate.
For invalid input:
400 Bad Request
For duplicate/conflicting data:
409 Conflict
For missing resources:
404 Not Found
Understanding status codes will make your APIs much easier for frontend developers to consume.
GET vs POST: A Quick Mental Model
You can remember the basic difference like this:
GET
Client
|
| "Give me users"
↓
Server
|
↓
Users
POST:
POST
Client
|
| "Here is a new user"
| + request body
↓
Server
|
↓
Create user
For example:
GET /api/users
means:
Give me users.
While:
POST /api/users
with:
{
"name": "John",
"email": "john@example.com"
}
means:
Create a new user using this data.
Where Does the Request Body Go in a Real Application?
In a simple application, you might see everything in one file:
server.js
But production applications usually separate responsibilities.
For example:
Request
↓
Route
↓
Controller
↓
Service
↓
Model
↓
Database
A POST request might look like:
POST /api/users
↓
user.routes.js
↓
user.controller.js
↓
user.service.js
↓
User model
↓
MongoDB
The controller may receive:
req.body
and pass the data to a service.
This separation becomes important as the application grows.
What's Next?
Now that we understand:
GET
Route Parameters
Query Parameters
POST
Request Body
we can move to the next important Express.js concepts.
A natural learning path is:
GET
↓
Route Parameters
↓
Query Parameters
↓
POST
↓
Request Body
↓
PUT / PATCH
↓
DELETE
↓
Middleware
↓
Error Handling
↓
Router
↓
Controllers
↓
Services
↓
Database
The next logical topic is PUT and PATCH methods, where we'll learn how to update existing resources and understand the difference between replacing a resource and partially updating it.
Final Thoughts
The POST method is one of the most important parts of building APIs.
The basic Express code is simple:
app.post("/api/users", (req, res) => {
const data = req.body;
res.status(201).json({
message: "User created",
data
});
});
But there are several concepts working together:
POST
↓
Request
↓
Content-Type: application/json
↓
express.json()
↓
req.body
↓
Validation
↓
Business Logic
↓
Database
↓
Response
Once you understand this flow, creating APIs for users, products, blogs, orders, authentication, and many other resources becomes much easier.
The key things to remember are:
app.post()
→ Creates a POST route
express.json()
→ Parses JSON request bodies
req.body
→ Accesses data sent by the client
201
→ Common status code for successful resource creation
400
→ Invalid request data
409
→ Conflict, such as duplicate data
And most importantly:
Never blindly trust data coming from the client. Validate it before using or storing it.