I know this has been asked multiple times, but I have been looking around and still can't find an answer to my problem.
index.js file
const express = require("express");
require("dotenv").config({
path: ".env",
});
const PORT = process.env.PORT || 5000;
const runDatabase = require("./config/database");
const path = require('path')
const app = express()
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
// routers
const userRouter = require("./router/usersRouter");
const categoryRouter = require("./router/categoryRouter");
const productRouter = require("./router/productRouter");
app.use("/api", userRouter);
app.use("/api", categoryRouter);
app.use("/api", productRouter);
app.listen(PORT, () => {
runDatabase();
console.log(`πThe Backend Server is up and running on port ${PORT}π`);
});
controller file
exports.createCategory = async (req, res) => {
try {
const { title, sort } = req.body;
console.log(req.body); // print empty object
await categoryModel.create({
title,
sort,
});
return res.status(200).send("created");
} catch (err) {
return res.status(400).send(err.message);
}
};
Here is my code, when sending the request in JSON raw postman a response is what I need but when using a form-data it will return an empty body
this is happened when I send data with form-data
returned an empty body

this is happened when I send data with raw (Json)
returned what i need

If you use the option "x-www-form-urlencoded" I guess it will work. So here is the thing:
When you are using postman's "form-data" it will be considered as multipart/form-data for which you need a library to parse form-data such as multer.
For x-www-from-urlencoded raw data, you can parse the data using the express
built-in middlewares or use a body-parser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With