-
Notifications
You must be signed in to change notification settings - Fork 0
DNET_JavaScriptHTTPClient
JavaScript の HTTP Client も色々ある。
| # | 非同期呼出の実現方式 | 外部のパッケージ(便利) | 組込み(基礎的) |
|---|---|---|---|
| 1 | コールバック | jQuery | xhr |
| 2 | Promise (JavaScript) | axios | fetch |
-
react_template
- https://github.com/OpenTouryoProject/FrontendTemplates/blob/develop/UI/SPA/React/react_template/src/common.js
- https://github.com/OpenTouryoProject/FrontendTemplates/blob/develop/UI/SPA/React/react_template/src/components/CrudSample.js
- https://github.com/OpenTouryoProject/FrontendTemplates/blob/develop/UI/SPA/React/react_template/src/components/CrudSample2.js
-
redux_template
- https://github.com/OpenTouryoProject/FrontendTemplates/blob/develop/UI/SPA/React/redux_template/src/common.js
- https://github.com/OpenTouryoProject/FrontendTemplates/blob/develop/UI/SPA/React/redux_template/src/components/CrudSample.js
- https://github.com/OpenTouryoProject/FrontendTemplates/blob/develop/UI/SPA/React/redux_template/src/components/CrudSample2.js
→ クロスドメイン
- 参考
- Fetch: クロスオリジン(Cross-Origin) リクエスト
https://ja.javascript.info/fetch-crossorigin
- Fetch: クロスオリジン(Cross-Origin) リクエスト
- Fetch API - Web API | MDN
https://developer.mozilla.org/ja/docs/Web/API/Fetch_API
(元 Wiki では未記載)
-
以下を見ると、クライアント側は特に何もしなくて良さそう。
-
参考
- corsに悩まされるな。axios でcorsを攻略する - Qiita
https://qiita.com/inatatsu_csg/items/15f63be00096ec21535e - axios で CORS によるクロスドメイン通信するとき - Qiita
https://qiita.com/naoiwata/items/59f2a7b2899ec8fef975
- corsに悩まされるな。axios でcorsを攻略する - Qiita
- axios/axios: Promise based HTTP client for the browser and node.js
https://github.com/axios/axios
HTTPリクエストを使用してデータを取得するajax の最も低レベルな実装。
以下の様なメソッドも存在する。
- jQuery.get()
- jQuery.post()
以下のjQuery.ajaxによるPOSTのサンプル・スニペットを使用すれば色々なパターンを処理可能。
$('#btnTest').click(function () {
$.ajax({
type: 'post',
url: 'http://・・・',
crossDomain: true,
contentType: 'application/x-www-form-urlencoded',
headers: {
'Authorization': 'Bearer ' + token
},
data: {
client_id: '・・・',
client_secret: '・・・',
},
xhrFields: {
withCredentials: true
},
success: function (responseData, textStatus, jqXHR) {
alert(textStatus + ', ' + responseData);
},
error: function (responseData, textStatus, errorThrown) {
alert(textStatus + ', ' + errorThrown.message);
}
});
});上記を、GETもイケるよう、改造した。
urlに'get'を、postdataにはnullを指定する。
function CallOAuthAPI(url, httpMethod, postdata) {
$.ajax({
type: httpMethod,
url: url,
crossDomain: true,
headers: {
'Authorization': 'Bearer ' + token
},
data: postdata,
xhrFields: {
withCredentials: true
},
success: function (responseData, textStatus, jqXHR) {
alert(textStatus + ', ' + responseData);
},
error: function (responseData, textStatus, errorThrown) {
alert(textStatus + ', ' + errorThrown.message);
}
});
}以下は、Web Storageからkey, valueをJSONでPOSTする例。
JSON文字列へのシリアライズ処理には JSON.stringify()(JSONのparseを色々試してみた。の該当節を参照)を使用する
// ---------------------------------------------------------------
// Web Storageからkey, valueをJSONでPOSTする。
// ---------------------------------------------------------------
// 引数 url : POST先のURL
// 戻り値 -
// ---------------------------------------------------------------
function PostJsonWebStorage(url) {
// Web Storageのすべての情報の取得
var jsonArray = new Array();
for (var i = 0; i < storage.length; i++) {
var _key = storage.key(i);
// Web Storageのキーと値を表示
var jsonBean = {
key: _key,
value: storage.getItem(_key)
};
jsonArray.push(jsonBean);
}
// <p id="url"></p> に表示
if (document.getElementById("url") != null) {
$("#url").text(url);
}
// <p id="request"></p> に表示
if (document.getElementById("request") != null) {
$("#request").text("request:" + JSON.stringify(jsonArray).toString());
}
CallService("POST", url, JSON.stringify(jsonArray), "application/json; charset=utf-8", "JSON", false);
}
// ---------------------------------------------------------------
// ajax
// ---------------------------------------------------------------
// 引数
// Type : GET or POST or PUT or DELETE verb
// Url : Location of the service
// Data : Data sent to server
// ContentType : Content type sent to server
// DataType : Expected data format from server
// ProcessData : True or False
// 戻り値 -
// ---------------------------------------------------------------
function CallService(Type, Url, Data, ContentType, DataType, ProcessData) {
$.ajax({
type: Type,
url: Url,
data: Data,
cache: false,
contentType: ContentType,
dataType: DataType,
processdata: ProcessData,
success: function (data) {
// On Successfull service call
ServiceSucceeded(data);
},
error: function (data) {
// When Service call fails
ServiceFailed(data);
}
});
}-
crossDomain: trueを追加する。
-
下位がxhr (XMLHttpRequest)なので
- XDomainRequest等の切り替えは自動的に行われる。
- 対応したカスタムヘッダ設定が必要なこともある。
-
参考
- javascript - jQueryのcrossDomainオプションが効かない - スタック・オーバーフロー
- [jquery] ajaxのクロスドメイン対応における
「プリフライトの動作」の有無について:なんとなしの日記
http://babyp.blog55.fc2.com/blog-entry-979.html
- サーバにデータを送信する際に用いるcontent-typeヘッダの値
- 既定値は"application/x-www-form-urlencoded"。
- JSONを送信する場合は"application/json"とする。
- サーバから返されるデータの型を指定する。
- 既定値ではjQueryがMIMEタイプなどを見ながら自動的に判別。
- JSONを受信する場合は"json"とすると、JavaScriptのオブジェクトに変換される。
-
jQuery API Documentation
- jQuery.ajax()
http://api.jquery.com/jquery.ajax/ - jQuery.get()
http://api.jquery.com/jQuery.get/ - jQuery.post()
http://api.jquery.com/jQuery.post/
- jQuery.ajax()
-
jQuery 日本語リファレンス
- jQuery.ajax(options) - jQuery 日本語リファレンス
http://semooh.jp/jquery/api/ajax/jQuery.ajax/options/ - jQuery.get( url, data, callback ) - jQuery 日本語リファレンス
http://semooh.jp/jquery/api/ajax/jQuery.get/+url%2C+data%2C+callback+/ - jQuery.post( url, data, callback, type ) -
http://semooh.jp/jquery/api/ajax/jQuery.post/+url%2C+data%2+callback%2C+type+/
- jQuery.ajax(options) - jQuery 日本語リファレンス
-
javascript - Differences between contentType and dataType in jQuery ajax function - Stack Overflow
(元 Wiki に URL の記載なし)
-
Ajaxの基幹技術。
-
JavaScriptなどのブラウザ上のスクリプト言語から
HTTP通信を行うための、組み込みオブジェクト(API)。
(元 Wiki では未記載)
-
XMLHttpRequest Level 2ではクロスドメインへのアクセスに対応
-
IE8, 9では XMLHttpRequest の代わりに XDomainRequest を使う
-
(X-Requested-Withのような)カスタムヘッダを付けるとGETリクエストでもプリフライトする。
-
参考
- XMLHttpRequest Level2 + CORSの時の設定メモ - blog::wnotes.net
https://blog.wnotes.net/posts/xhr-lv2-cors-settings/
- XMLHttpRequest Level2 + CORSの時の設定メモ - blog::wnotes.net
-
XMLHttpRequest - Web API | MDN
https://developer.mozilla.org/ja/docs/Web/API/XMLHttpRequest -
XMLHttpRequest - Wikipedia
https://ja.wikipedia.org/wiki/XMLHttpRequest
- ajaxまとめ(xhr, jquery, axios, fetch) | 感情的プログラミング伝記
| タウン情報誌 AIR函館 - 北海道函館市の食・呑・遊をご紹介!
https://www.air-h.jp/articles/emopro/ajax%E3%81%BE%E3%81%A8%E3%82%81xhr-jquery-axios-fetch/
- CORS (Cross-Origin Resource Sharing) - マイクロソフト系技術情報 Wiki
移行メモ
- 「JSON文字列へのデシリアライズ処理には JSON.stringify() を使用する」は、
JSON.stringify()がシリアライズ(JSON 文字列化)を行うメソッドのため 「シリアライズ処理」に修正した。- 参考の「javascript - Differences between contentType and dataType in jQuery ajax function - Stack Overflow」は、URL の位置に同じ表題が入っており リンク先が不明のため、その旨を注記した。
- 「サンプル」(axios / xhr)は「...。」のみだったため、未記載である旨を明示した。
- 同名の見出し(「サンプル」「クロスドメイン」「参考」)が複数あり GitHub Wiki でアンカが衝突するため、括弧で文脈を補って一意にした。
- マイクロソフト系技術情報 Wiki(techinfoofmicrosofttech.osscons.jp)への URL リンクは、移行済みの CORS (Cross-Origin Resource Sharing) / JSONのparseを色々試してみた。 に張り替えた。
- PukiWiki のページ内アンカ(
#xxxxxxxx)は GitHub Wiki では再現できないため、 同一ページ内のアンカは見出しから生成されるアンカに張り替えた。
Tags: 移行, JavaScript, HTTP Client, fetch, axios, jQuery, XMLHttpRequest, Ajax, CORS
このWikiは「Open棟梁Project」,「OSSコンソーシアム 開発基盤部会」によって運営されています。