JQuery API and Google URL Shortener API

I am trying to shorten the url using the http://goo.gl API with the following jQuery function

 $.ajax({ url: 'https://www.googleapis.com/urlshortener/v1/url?key=MY_API_KEY', crossDomain: true, type: 'POST', contentType: 'application/json', data: '{longUrl:"'+encodeURI(url)+'"}', dataType: 'jsonp', success: function(e) { alert(JSON.stringify(e)); } }); 

And I get the following error in JSON:

 {"error":{"errors":[{"domain":"global","reason":"required","message":"Required parameter: shortUrl","locationType":"parameter","location":"shortUrl"}],"code":400,"message":"Required parameter: shortUrl"}} 

Why is he requesting a short url? What am I doing wrong?

+6
source share
2 answers

You cannot perform cross-domain POST in JavaScript. What jQuery really does is when you indicate that crossDomain is true and dataType is jsonp is a jsonp request which is just a hack to get data from another server using a tag. You get this error because it is as if you just made GET requests on an API page without parameters. The other server must be aware of this and must support it.

There is no mention of jsonp on the Goo.gl API page, which makes me think that it does not support it. It would be best to write a proxy server in PHP to execute the requests for you and return the result, and then make an Ajax call in this PHP file.

Edit: If this is a Chrome extension, you can make a cross-domain Ajax call using the Chrome special method to get the URL to go to the Ajax object. You also need to add the remote URL to the extension manifest file, as registered here.

+6
source

Here is the working code.

 $.ajax({ url: 'https://www.googleapis.com/urlshortener/v1/url?key={API-KEY}', type: 'POST', contentType: 'application/json; charset=utf-8', data: '{ longUrl: "' + longURL +'"}', success: function(response) { $('#inputBox').val(response.id); } }); 
+3
source

Source: https://habr.com/ru/post/892836/


All Articles