AJAX发布请求使用qwest.js到goo.gl url shortener api

AJAX post request using qwest.js to goo.gl url shortener api

本文关键字:goo js gl url api shortener qwest 布请求 请求 AJAX      更新时间:2023-09-26

我正在尝试使用开源库(qwest.js)goo.gl URL Shortener API来缩短URL。不过,我已经使用jquery成功地实现了这一点,但使用qwest时会出现错误"This API不支持解析表单编码的输入。"。

我的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");
});

以及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
                    });

强烈建议您提供任何帮助。

这里是qwest的作者;)

如文件所述:the default Content-Type header is application/x-www-form-urlencoded for post and xhr2 data types, with a POST request

但是Google Shortener服务不接受它。我想它想要一个JSON输入类型。然后您应该将qwest的dataType选项设置为json。此外,您的responseType选项无效,并且没有遵循文档。通常,如果Google使用有效的Content-Type标头回复请求,则不必设置它。这是一个好代码:

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

在Google没有发送已识别的Content-Type的情况下,只需将responseType选项也设置为json即可。