2

I am trying to upload an image. Normally I use axios call api. Since This call is not working with axios I tried with fetch.

I want to know what the difference between these two

Here are these two.

Axios // API CALL WITH NOT SUCCESSFUL WITH THIS ONE

axios
  .post(
    "userapi/UpdateUserProfileImage",
    {
      body: createFormData(photo, {}),
    },
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  )
  .then((res) => console.log(res.data))
  .catch((err) => console.log(err.response.data.Message));

Here is the fetch method. // this will successful

fetch("userapi/UpdateUserProfile", {
  method: "POST",
  headers: new Headers({
    "Content-Type": "multipart/form-data",
  }),
  body: createFormData(photo, {}),
})
  .then((data) => data.json())
  .then((res) => {
    console.log("upload succes", res);
  })
  .catch((error) => {
    console.log("upload error", error);
  });

What the difference between these two?

Here is the error when I use axios to call API.

Index was out of range. Must be non-negative and less than the size of the collection

Phil
  • 157,677
  • 23
  • 242
  • 245
Kerry
  • 384
  • 3
  • 25
  • Where is this code running? In the browser, Node or some other device (eg react-native)? – Phil Apr 08 '22 at 05:14
  • Is server obtains same data in both cases? – 1_bug Apr 08 '22 at 05:15
  • A simple typo but one that seems very prevalent. Don't wrap the Axios `data` param in an object. You can generally omit the content-type header for both requests as well. You really only need `axios.post(url, createFormData(photo, {}))` – Phil Apr 08 '22 at 05:15
  • 3
    Your End Point seems to be different. In axios - `UpdateUserProfileImage` and in fetch it is - `UpdateUserProfile` – swapnesh Apr 08 '22 at 05:16
  • Well, the error is from the server message is sent from the server, so it's sort of difficult to figure this out. Try it in a request client like Postman, and when it works, convert it to Axios one by one. – code Apr 08 '22 at 05:16

0 Answers0