Giphy uplaod works with .ajax but not fetch

58 views Asked by At

I am trying to upload a gif to Giphy. It works using jQuery/.ajax but I can't get it to work with fetch.

Here is the .ajax version:

$.ajax({
    type: "POST",
    url: "http://upload.giphy.com/v1/gifs",
    data: {
      api_key: "E0sxxxxxxxxxxxxxxxxxxxxxxxxxx",
      source_image_url: "https://urlto/snoopy.gif",
      tags: "cute dog",
    },
    success: function (data) {
      console.log(data);
    },
    error: function (data) {
      alert("fail");
    },
  });

and here is the fetch version which returns a 401 error:

 fetch("https://upload.giphy.com/v1/gifs", {
    method: "POST",

    body: {
      api_key: "E0sxxxxxxxxxxxxxxxxxxxxxxxxxx",
      source_image_url: "https://urlto/snoopy.gif",
      tags: "cute dog",
    },

  }).then((response) => {
    console.log("status:");
    console.log(response);
  });

I'm am not schooled on fetch so any help with what I am doing wrong would be great.

1

There are 1 answers

0
Musa On BEST ANSWER

You can't pass a plain object as the request body to fetch as you do in $.ajax. Use a URLSearchParams object

 fetch("https://upload.giphy.com/v1/gifs", {
    method: "POST",
    body: new URLSearchParams({
      api_key: "E0sxxxxxxxxxxxxxxxxxxxxxxxxxx",
      source_image_url: "https://urlto/snoopy.gif",
      tags: "cute dog"
    })    
  }).then((response) => {
    console.log("status:");
    console.log(response);
  });