Search code examples
reactjsfetchhttprequestmultipartform-dataform-data

How to post data when you have javascript object using multipart/form-data content-type


So I have never post a data using FormData and multipart/form-data as Content-Type in my React project. But now I'm kinda forced by backend to send it this way since we have some images in payload.

The problem is that the whole data is a JS object and can be parsed to JSON, and nothing more. So how can I convert my JS object into a valid FormData that backend would accept it? Everything works without a problem in Postman, but in the app I always get the same error.

Here is some more detail:

The working Postman sample:

enter image description here

What I expect to be working (but obviously doesn't):

const createProd = () =>
  HttpRequest.post('/api/prod', {
    body: {
      Product: {
        title: 'Test Prod',
        shop: null,
        description: "My new ad's description",
        category: { id: '5d8c6aa6fadeaf26b0194667' },
        condition: 'USED'
       }
    });

HttpRequest is a helper function which uses ES6 fetch for requests.

I always get the same error: "Required request part 'Product' is not present" with/without JSON.stringify.

I even tried to create a sample FormData to at least change the error:

cont payload = new FormData();
payload.append('Product', {foo: 'bar'});

But still same error. I also copied the code which is generated by Postman. But still no chance.

I would be thankful if you share your suggestions or workarounds.

Thanks in advance.


Solution

  • const formData = new FormData();
    const product = { //your product object };
    formData.append('product', JSON.stringify(product));
    
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data; charset=utf-8; boundary="another cool boundary";'
      }
    };
    axios.post(`/api/ads`, formData, config).then((res) => {
      console.log(res);
    }).catch(err => {
      console.log(err);
    });
    

    Maybe you should set header. Try this one. In my case I used Axios. It worked for me in my project.