2016-03-21 2 views
1

APIキーを使用しているので、私はAngularアプリケーションでGoogleのURL Shortenerを使用しています。使用しているサーバー側でgoogle apiコールを行う方がスマートで安全です角度。ノードリクエスト - そしてGoogle URLショートネクタ

見つかった$http非常にまっすぐ進むが、ノードではすぐにわかった。npmパッケージrequestを使うのが良いとすぐに分かった。

だから基本的に私は実行する必要があります。

POST https://www.googleapis.com/urlshortener/v1/url 
Content-Type: application/json 
{"longUrl": "http://www.google.com/"} 

そして、私が現在書いている:

//Load the request module 
var request = require('request'); 

//Configure and make the request 
request({ 
     url: 'https://www.googleapis.com/urlshortener/v1/url?key=XXXXXXXXX', 
     method: 'POST', 
     headers: { //We can define headers too 
     'Content-Type': 'application/json' 
     }, 
     data: { 
     'longUrl': 'http://www.myverylongurl.com' 
     } 
    }, function(error, response, body){ 
     if(error) { 
      console.log(error); 
     } else { 
      console.log(response.statusCode, response.body); 
     } 
}); 

を私はエラーを取得しておいてください。

"errors": [{ "domain": "global", "reason": "required", "message": "Required", "locationType": "parameter”, “location": "resource.longUrl" 
}] 

は私の要求を間違ってますか?

ありがとうございました。

+1

質問は何ですか? – Cohars

+0

質問を更新しました。ありがとう – userMod2

+0

アクセストークンを取得していますか? cf [承認リクエスト](https://developers.google.com/url-shortener/v1/getting_started#OAuth2Authorizing) –

答えて

1

request documentationによると、jsonオプションを使用してJSONデータを送信できます。あなたのケースでは

json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.

次のようになります。

request.post('https://www.googleapis.com/urlshortener/v1/url?key=xxxx', { 
    json: { 
    'longUrl': 'http://www.hugocaillard.com' 
    } 
}, function (error, response, body) { 
    if(error) { 
    console.log(error) 
    } else { 
    console.log(response.statusCode, body) 
    } 
}) 

注:あなたも(私はすべてがjson:data:を変えた)request()メソッドを使用しますが、ここでは十分に機能request.post()ことができます。

+0

ああ - それを逃した! ありがとうございました – userMod2

+0

はい、 'request'使用法文書では明らかではありません。どういたしまして! – Cohars

関連する問題