1

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.

2
  • What is this HttpRequest? Is it axios? Where did you try to put this JSON.stringify? Inside body? What backend language do you use? Did you try adding headers to your request? Commented Nov 11, 2020 at 16:02
  • 1
    @k-wasilewski I mentioned that I'm using fetch in my React project. I also mentioned that I tried it with/without JSON.stringfy. Anyway, I used axios and my problem solved. Commented Nov 13, 2020 at 21:54

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I guess using axios and not fetch was the key of my problem. Probably there are some ways of using fetch but they may not be as straightforward as the way we can do it with axios.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.