Parse - Cloud Code - Networking
Networking
Cloud CodeではParse.Cloud.httpRequestを使うことで、HTTPサーバに対してHTTPリクエストを送信できます。このファンクションはオプションオブジェクトを設定値として呼び出します。シンプルなGETリクエストは次のようになります。
Parse.Cloud.httpRequest({ url: 'http://www.parse.com/', success: function(httpResponse) { console.log(httpResponse.text); }, error: function(httpResponse) { console.error('Request failed with response code ' + httpResponse.status); } });
Query Parameters
オプションオブジェクトにparamsを設定することで、URLの後に付与するクエリパラメータを指定できます。JSONオブジェクトで指定する場合は次のようになります。
Parse.Cloud.httpRequest({ url: 'http://www.google.com/search', params: { q : 'Sean Plott' }, success: function(httpResponse) { console.log(httpResponse.text); }, error: function(httpResponse) { console.error('Request failed with response code ' + httpResponse.status); } });
文字列で指定する場合は次のようになります。
Parse.Cloud.httpRequest({ url: 'http://www.google.com/search', params: 'q=Sean Plott', success: function(httpResponse) { console.log(httpResponse.text); }, error: function(httpResponse) { console.error('Request failed with response code ' + httpResponse.status); } });
Setting Headers
オプションオブジェクトにheaders属性を設定すれば、HTTPヘッダを送信できます。Content-Typeヘッダを送信する場合は次のようになります。
Parse.Cloud.httpRequest({ url: 'http://www.example.com/', headers: { 'Content-Type': 'application/json' }, success: function(httpResponse) { console.log(httpResponse.text); }, error: function(httpResponse) { console.error('Request failed with response code ' + httpResponse.status); } });
Sending a POST Request
オプションオブジェクトにmethod属性を設定すればPOSTリクエストを送信できます。POSTのボディは、bodyを使って指定します。シンプルなPOSTリクエストは次のようになります。
Parse.Cloud.httpRequest({ method: 'POST', url: 'http://www.example.com/create_post', body: { title: 'Vote for Pedro', body: 'If you vote for Pedro, your wildest dreams will come true' }, success: function(httpResponse) { console.log(httpResponse.text); }, error: function(httpResponse) { console.error('Request failed with response code ' + httpResponse.status); } });
これはhttp://www.example.com/create_postに対して、url-form-encoded形式のボディをPOSTリクエストで送信します。ボディをJSON形式にする場合は次のようにします。
Parse.Cloud.httpRequest({ method: 'POST', url: 'http://www.example.com/create_post', headers: { 'Content-Type': 'application/json' }, body: { title: 'Vote for Pedro', body: 'If you vote for Pedro, your wildest dreams will come true' }, success: function(httpResponse) { console.log(httpResponse.text); }, error: function(httpResponse) { console.error('Request failed with response code ' + httpResponse.status); } });
body属性の値に文字列で指定することもできます。
The Response Object
successやerrorの際、レスポンスオブジェクトが戻ります。レスポンスオブジェクトは以下のプロパティを含みます。
- status - HTTPレスポンスステータス
- headers - レスポンスヘッダ
- text - レスポンスボディ
- data - 解析したレスポンス。ただし、送信されたcontent-typeがCloud Codeによって解析できた場合に限る