snapshot of postman req.body is empty when I send data using form-data in my Express.js application. However, when I send data using raw JSON, I receive the expected object in req.body. Here’s my setup:
This is my index.js
require("dotenv").config();
const express = require("express");
const server = express();
const cors = require("cors");
const port = process.env.PORT || 3000;
const bodyParser = require("body-parser");
//database
require("./db/conn");
//middlewares
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.use(cors());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
//routes
const userRouter = require("./routes/UserRoutes");
const authRouter = require("./routes/AuthRouter");
server.use("/user", userRouter);
server.use("/auth", authRouter);
server.listen(port, () => {
console.log(`server started at http://localhost:${port}`);
});
This is route
const express = require("express");
const router = express.Router();
const { Auth } = require("../middlewares/auth");
const {
Login,
UpdateUser,
Dashboard,
Register,
Posts,
} = require("../controllers/UserController");
router.post("/register", Register);
router.post("/login", Login);
router.put("/update/:id", Auth, UpdateUser);
router.get("/dashboard", Auth, Dashboard);
router.get("/getposts", Auth, Posts);
module.exports = router;
This is controller
const UserModel = require("../model/userModel");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const Register = async (req, res) => {
console.log(req.body);
res.send(req.body);
const { name, email, password } = req.body;
// if (!name || !email || !password) {
// return res.status(400).json({ error: "All fields are required" });
// }
// try {
// const user = await UserModel.findOne({ email });
// if (user) {
// return res.status(400).json({ error: "User already exists" });
// }
// const hashedPassword = await bcrypt.hash(password, 10);
// const newUser = new UserModel({
// name,
// email,
// password: hashedPassword,
// });
// const saveUser = await newUser.save();
// res
// .status(201)
// .json({ message: "User registered successfully", user: saveUser });
// } catch (error) {
// res.status(500).json({ error: "Something went wrong at the server" });
// }
};
const Login = async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: "All fields are required" });
}
try {
const user = await UserModel.findOne({ email });
if (!user) {
return res.status(404).json({ error: "Invalid login details" });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ error: "Invalid login credentials" });
}
const payload = {
id: user.id,
email: user.email,
};
const accessToken = jwt.sign(payload, process.env.SECRET_KEY, {
expiresIn: "1m",
});
const refreshToken = jwt.sign(payload, process.env.SECRET_KEY, {
expiresIn: "10d",
});
res.status(200).json({
message: "login sucessfull",
isLogged: "true",
data: payload,
accesstoken: accessToken,
refreshtoken: refreshToken,
});
} catch (error) {
res.status(500).json({ error: "Something went wrong at the server" });
}
};
const UpdateUser = async (req, res) => {
const userId = req.params.id;
req.body.password = await bcrypt.hash(req.body.password, 10);
try {
const user = await UserModel.findOne({ _id: userId });
if (!user)
return res.status(500).json({ message: "no user found with this id" });
const updatedUser = await UserModel.findOneAndUpdate(
{ _id: userId },
req.body,
{
new: true,
}
);
if (updatedUser) {
return res
.status(200)
.json({ message: "user updated sucessfully", data: updatedUser });
}
} catch (e) {
return res
.status(500)
.json({ message: "something went bad at server " + e });
}
};
const Dashboard = async (req, res) => {
res.status(200).json({ message: "Welcome to the dashboard" });
};
const Posts = async (req, res) => {
res.status(200).json({ message: "post request" });
};
const getAllData = async (req, res) => {
res.status(200).json({ message: "get data" });
};
module.exports = { Login, UpdateUser, Dashboard, Posts, Register };
I’ve already tried adjusting the middleware order, but the issue persists. Any insights into what might be causing this problem would be greatly appreciated.
2
Answers
After adding multer middlware its working fine (Multer.js)
This code here is for handling files
above code is for handling files .since im handling files on my project im using above configuration u can omit the configuration . refer https://www.npmjs.com/package/multer for more information Im using this midleware in routes here
im using upload on router.post("/register,upload,Register). things working fine.
if u send data through postman via form-data use multer middlware . express by default accepts only raw data in json format .
When sending data to Express.js, if you’re using the FormData() API, Use a middleware like
Formidable()
to gather data inreq.fields
rather thanreq.body
.For example: