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

标签 javascript jquery ajax google-url-shortener

我正在尝试使用开源库 (qwest.js) goo.gl URL Shortener API 来缩短 URL。虽然我已经使用 jquery 成功实现了它,但是它给了我错误“这个 API 不支持解析表单编码的输入。”使用 qwest 完成后。

我的 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 的作者 ;)

如文档中所述:对于 post 和 xhr2 数据类型,默认的 Content-Type header 是 application/x-www-form-urlencoded,带有 POST 请求

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

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

如果 Google 未发送可识别的 Content-Type,只需将 responseType 选项也设置为 json

关于javascript - 使用 qwest.js 的 AJAX 发布请求到 goo.gl url shortener api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172753/

相关文章:

javascript - jQuery 在修改 xml 时如何存储用作上下文参数的 xml?

javascript - 在渲染内 react 三元

javascript - 寻找一个公式来检查一个数字是否是 2 或更大的数字乘以 3 或更大的数字的乘积

javascript - `iframe` 事件监听器如何检测到 `escape` 按键事件?

jquery - 是否可以在 render partial 中传递参数?

jQuery: "input[@checked], input[@type=' 文本']“查找是什么?

javascript - AngularJS 指令中的单元测试私有(private)函数

javascript - 是否可以在动态添加的文本输入上全局捕获 keydown?

javascript - 如何在 Codeigniter 上进行 Ajax

c# - Controller 未收到英国格式的 MVC3 日期