現在、Google URL Shorter を使用して 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'
});
};