Search code examples
jquerygoogle-url-shortener

Google URL Shortener Bad Request with jQuery


I'm currently having some problems to shorten a URL with the Google URL shortener.

I'm using CoffeeScript but the generated code seems good. Here is what I do:

shortenUrl = (longUrl) ->
  $.ajax(
    type: 'POST'
    url: "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey" 
    data:
        longUrl: longUrl
    dataType: 'json'
    success: (response) -> 
      console.log response.data
    contentType: 'application/json'
 );

The generated code is:

shortenUrl = function(longUrl) {
  return $.ajax(console.log({
    longUrl: longUrl
  }), {
  type: 'POST',
  url: "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey",
  data: {
    longUrl: longUrl
  },
  dataType: 'json',
  success: function(response) {
    return console.log(response.data);
  },
  contentType: 'application/json'
});

};

Here is the error I get in the JS Chrome console :

POST https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey 400 (Bad Request)

(precisely, there is apparently a Parse error)

Note that, when I execute a curl request like this :

curl https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey \
    -H 'Content-Type: application/json' \
    -d '{longUrl: "http://www.google.com/"}'

It works like a charm. And I get :

{
    "kind": "urlshortener#url",
    "id": "http://goo.gl/fbsS",
    "longUrl": "http://www.google.com/"
}

So, what's wrong with this jQuery ? (I'm using version 1.9.x)

EDIT: Here is the correct way to do it with jQuery :

shortenUrl = function(longUrl) {
    return $.ajax(console.log({
      longUrl: longUrl
    }), {
    type: 'POST',
    url: "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey",
    data: '{ longUrl: longUrl }', // <-- string here
    dataType: 'json',
    success: function(response) {
      return console.log(response.data);
    },
    contentType: 'application/json'
  });
};

Solution

  • Ok.. I just found where was my error. Sorry for that, I couldn't imagine that jQuery was so $%@£...

    the data variable that I pass is actually a Js Object (which I assumed it was interpreted as JSON on the server...it wasn't)

    data param must be a string, containing "plain" json.

    Now it works :)