Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send FormData in MERN Stack project with TS

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
}

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading