I'm trying to send FormData to my backend but when I console.log the req.body it's empty object and I don't know why.
Here is my frontend request:
const createProduct = (e: any) => {
e.preventDefault();
const data = new FormData()
data.append("name", name)
data.append("description", description)
data.append("price", price)
for (const colorAndImage of colorsAndImages) {
data.append('images', colorAndImage.images[0]);
data.append('colors', colorAndImage.colors);
}
data.append("type", type)
fetch('http://localhost:4000/products/create', {
method: 'POST',
body: data
})
Here is how the image file looks like in the console:
File {name: 'iphone_13_pro_max_gold_pdp_image_position-1a__wwen_5.jpg', lastModified: 1642862621798, lastModifiedDate: Sat Jan 22 2022 16:43:41 GMT 0200 (Eastern European Standard Time), webkitRelativePath: '', size: 22194, …}
Here is what I'm sending in the request in Network tab:
name: sdf
description: sdf
price: 234
images: (binary)
colors: red
type: sdf
Here is the controller in backend side:
productController.post('/create', async (req: Request, res: Response) => {
console.log(req)
try {
const data = req.body;
let product = await create(data)
res.status(201).json(product)
} catch (error) {
console.log(error);
//res.status(500).json({error: error})
}
})
And what I see when I try to console.log the request:
{
name: undefined,
description: undefined,
price: undefined,
colors: undefined,
images: undefined,
type: undefined,
likes: undefined
}
Error: Product validation failed: name: Path `name` is required., description: Path `description` is required., price: Path `price` is required., type: Path `type` is required.
My express config:
const corsConfig: cors.CorsOptions = {
credentials: true,
origin: ['http://localhost:3000', 'http://localhost:2000']
}
export default function (app: Application) {
app.use(cors(corsConfig))
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(express.json())
app.use(auth())
}
CodePudding user response:
Not sure why are you using FormData in sending raw data from frontend to backend.
FormData is generally used when you have to send (upload) files. For simple data you can just send JSON object.
Express by default can't parse multipart/form-data
, you will have to install a middleware like multer in order to get the data or you can update your data structure in frontend.
let dataToSend = {
name: name,
description: description,
price: price
// Rest of the properties
}