Note that there are some explanatory texts on larger screens.

plurals
  1. POGoogle URL Shortener Bad Request with jQuery
    primarykey
    data
    text
    <p>I'm currently having some problems to shorten a URL with the Google URL shortener.</p> <p>I'm using CoffeeScript but the generated code seems good. Here is what I do:</p> <pre><code>shortenUrl = (longUrl) -&gt; $.ajax( type: 'POST' url: "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey" data: longUrl: longUrl dataType: 'json' success: (response) -&gt; console.log response.data contentType: 'application/json' ); </code></pre> <p>The generated code is:</p> <pre><code>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' }); </code></pre> <p>};</p> <p>Here is the error I get in the JS Chrome console :</p> <pre><code>POST https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey 400 (Bad Request) </code></pre> <p>(precisely, there is apparently a Parse error)</p> <p>Note that, when I execute a curl request like this :</p> <pre><code>curl https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey \ -H 'Content-Type: application/json' \ -d '{longUrl: "http://www.google.com/"}' </code></pre> <p>It works like a charm. And I get :</p> <pre><code>{ "kind": "urlshortener#url", "id": "http://goo.gl/fbsS", "longUrl": "http://www.google.com/" } </code></pre> <p>So, what's wrong with this jQuery ? (I'm using version 1.9.x)</p> <p>EDIT: Here is the correct way to do it with jQuery :</p> <pre><code>shortenUrl = function(longUrl) { return $.ajax(console.log({ longUrl: longUrl }), { type: 'POST', url: "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey", data: '{ longUrl: longUrl }', // &lt;-- string here dataType: 'json', success: function(response) { return console.log(response.data); }, contentType: 'application/json' }); }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload