【问题标题】:Google URL Shortener Bad Request with jQuery使用 jQuery 的 Google URL Shortener 错误请求
【发布时间】:2013-04-18 16:01:12
【问题描述】:

我目前在使用 Google 网址缩短器缩短网址时遇到一些问题。

我正在使用 CoffeeScript,但生成的代码看起来不错。这是我的工作:

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'
 );

生成的代码是:

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'
});

};

这是我在 JS Chrome 控制台中遇到的错误:

POST https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey 400 (Bad Request)

(确切地说,显然存在 Parse 错误)

请注意,当我执行这样的 curl 请求时:

curl https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey \
    -H 'Content-Type: application/json' \
    -d '{longUrl: "http://www.google.com/"}'

它就像一个魅力。我得到了:

{
    "kind": "urlshortener#url",
    "id": "http://goo.gl/fbsS",
    "longUrl": "http://www.google.com/"
}

那么,这个 jQuery 有什么问题? (我使用的是 1.9.x 版本)

编辑: 这是使用 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'
  });
};

【问题讨论】:

标签: jquery google-url-shortener


【解决方案1】:

好的.. 我刚刚发现我的错误在哪里。抱歉,我无法想象 jQuery 如此 $%@£...

我传递的数据变量实际上是一个 Js 对象(我认为它在服务器上被解释为 JSON...它不是)

数据参数必须是字符串,包含“普通”json。

现在可以了:)

【讨论】:

  • 正确的做法是在 cURL 请求中。 data 参数中传递的数据(在 jQuery ajax 对象中)必须是字符串(包含 json),而不是 javascript 对象。对不起,我会编辑它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 2016-02-26
相关资源
最近更新 更多