Google URL Shortener Bad Request with jQuery -
i'm having problems shorten url google url shortener.
i'm using coffeescript generated code seems good. here 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 error in js chrome console :
post https://www.googleapis.com/urlshortener/v1/url?key=myapikey 400 (bad request) (precisely, there apparently parse error)
note that, when execute curl request :
curl https://www.googleapis.com/urlshortener/v1/url?key=myapikey \ -h 'content-type: application/json' \ -d '{longurl: "http://www.google.com/"}' it works charm. , :
{ "kind": "urlshortener#url", "id": "http://goo.gl/fbss", "longurl": "http://www.google.com/" } so, what's wrong jquery ? (i'm using version 1.9.x)
edit: here correct way 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' }); };
ok.. found error. sorry that, couldn't imagine jquery $%@£...
the data variable pass js object (which assumed interpreted json on server...it wasn't)
data param must string, containing "plain" json.
now works :)
Comments
Post a Comment