1024programmer Java AJAX post request goo.glurlshortenerapi using qwest.js

AJAX post request goo.glurlshortenerapi using qwest.js

I am trying to shorten URLs using goo.gl URL Shortener API, which is an open source library (qwest.js). I have successfully implemented it using jquery, but it gives me the error “This API does not support parsing form encoding input.” when done using qwest.

My code uses jquery:

var lOngURL= "http://www.google.com/";
  $.ajax({
         url: 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
         type: 'POST',
         contentType: 'application/json; charset=utf-8',
         data: '{ longUrl:"'+ longURL+'"}',
         success: function(response) {
           console.log(response)
         }
  })
 .done(function(res) {
     console.log("success");
 })
 .fail(function() {
     console.log("error");
 })
 .always(function() {
     console.log("complete");
 });
 

Non-working code with qwest.js

var lOngURL= "http://www.google.com/"
 qwest.post('https://www.googleapis.com/urlshortener/v1/url?key=479dfb502221d2b4c4a0433c600e16ba5dc0df4e&',
     {longUrl: longURL},
     {responseType:'application/json; charset=utf-8'})
                     .then(function(response) {
                         // Make some useful actions
                     })
                     .catch(function(e, url) {
                         // Process the error
                     });
 

Any help is highly recommended.

1> Xiaozhi..:


The author of qwest is here 😉

As stated in the documentation:the default Content-Type header is application/x-www-form-urlencoded for post and xhr2 data types, with a POST request.

But the Google Shortener service doesn’t accept it. I assume it wants a JSON input type. Then you should set the dataType option of qwest to json. Also, your responseType option is invalid and does not follow the documentation. Normally, if Google replies to a request with a valid Content-Type header, there is no need to set it. This is good code:

qwest.post('https://www.googleapis.com/urlshortener/v1/url?key=479dfb502221d2b4c4a0433c600e16ba5dc0df4e&',
{longUrl: longURL},
{dataType:'json'})

If Google is not sending recognized content Content-Type, set the responseType option to json.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/759210

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索