2

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

我正在使用 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'
  });
};
4

1 回答 1

1

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

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

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

现在它可以工作了:)

于 2013-04-18T16:06:16.860 回答