0

I decided to try using jQuery for once because it was already included in the page. I found out that it has very convenient $.ajax method that allows you to produce readable Ajax calls.

I learned how to add custom headers to the call, since I need to authorize at Imgur. This is my code:

  $.ajax({
    url: 'https://api.imgur.com/3/image',
    type: 'POST',
    headers: {
      Authorization: 'Client-ID ' + APP_ID,
      Accept: 'application/json'
    },
    data: {
      image: SavePage.getimgrc(),
      type: 'base64'
    },
    success: function(result) {
      var id = result.data.id;
      window.location = 'https://imgur.com/gallery/' + id;
    }
  });

Well, no matter how convenient it is, it does not work as advertised:

POST /3/image HTTP/1.1
Host: api.imgur.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 20956
Origin: resource://jid0-gxjllfbcoax0lcltedfrekqdqpi-at-jetpack
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

So, is it broken or did I screw it up?

Community
  • 1
  • 1
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Side note: Make user OPTIONS allow headers you want to set - http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working – Alexei Levenkov Oct 19 '14 at 18:58
  • Is that the output from your console? – Leo Bedrosian Oct 19 '14 at 18:58
  • Yes, it's firebug output. I don't understand the OPTIONS stuff. Why should I not be able to set any headers to request? – Tomáš Zato Oct 19 '14 at 19:03
  • @AlexeiLevenkov There was really some problem with that OPTIONS security overkill. jQuery can't handle it, but if I send native request, everything goes fine... – Tomáš Zato Oct 19 '14 at 19:17

1 Answers1

-1

So I have finally figured this out. The problem was, that despite my previous experiences, I was using jQuery. The native code works normally:

  var r = new XMLHttpRequest();
  r.open("POST", 'https://api.imgur.com/3/image');
  r.setRequestHeader("Authorization", 'Client-ID ' + APP_ID);
  r.setRequestHeader("Accept", 'application/json ');

  var data = new FormData();
  data.append("type", "base64");
  data.append("image", SavePage.getimgrc());

  r.send(data);

Lesson learned: The fact that the jQuery is included on the site doesn't mean it will help you.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778