我目前在缩短使用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'
});
};
答案 0 :(得分:1)
确定.. 我刚发现我的错误在哪里。对不起,我无法想象jQuery是如此$%@£...
我传递的数据变量实际上是一个Js对象(我假设它在服务器上被解释为JSON ......它不是)
data param必须是一个字符串,包含“plain”json。
现在有效:)