【发布时间】: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'
});
};
【问题讨论】:
-
在 ruby 中遇到同样的问题,请查看以下链接,stackoverflow.com/a/23562091/344993
标签: jquery google-url-shortener