Skip to content

Instantly share code, notes, and snippets.

@umamichi
Last active September 16, 2021 10:50
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umamichi/1e1f2d48d5e2a85041033619ea44a730 to your computer and use it in GitHub Desktop.
Save umamichi/1e1f2d48d5e2a85041033619ea44a730 to your computer and use it in GitHub Desktop.
fetch API

fetch API

▼fetch API とは?

XMLHttpRequest と似たもので、より強力で柔軟な操作が可能。
まだ実験段階の機能で、複数のブラウザで開発中の状態にあります。
caniuse: http://caniuse.com/#search=fetch
Service WorkersではXMLHttpRequestは使えないため、fetch APIが使わています。
Service Workers … ブラウザが Web ページとは別にバックグラウンドで実行するスクリプト。Web Pushなど)

▼fetch API の使い方

fetch('URLあるいは相対パスなど').then(function(response) {
  return response.json();
}).then(function(json) {
  // jsonにJSONオブジェクトで結果が渡される
  ...
});

まず、取得するリソースのパスを必ず引数で指定する。
呼び出し後、fetch() は Promise オブジェクトを返します。

// オプション指定も可能
fetch('URLあるいは相対パスなど', {/* JSONでオプションを指定 */}).then(...);

▼POSTメソッドでリクエストする

formタグのidを指定し、bodyにFormDataをわたす

fetch(url, {
  method: 'POST',
  body: new FormData(document.getElementById('<form>タグのid'))
}).then(function(response) {
  return response.json();
}).then(function(json) {
  ...
});

→実際にリクエストしてみる

▼リクエストするデータの型がなんか違う?

jQuery は Form Data

name:jquery post

fetch API は Request Payload

------WebKitFormBoundarym11KYh69UzlN4Z10
Content-Disposition: form-data; name="name"

fetch api
------WebKitFormBoundarym11KYh69UzlN4Z10--

それぞれ違う型になっていた

payloadとは?

payloadの意味は一般的にhttpリクエストのhttpヘッダーを除いたボディ部分です。つまり、"送信内容そのもの"です。

▼FormDataとpayloadの違い

Form Dataとは?

Form型に変換されたデータ。
Content-type: 'application/x-www-form-urlencoded' とすることでForm型のデータになる
POSTでリクエストすると一般的にContent-type: 'application/x-www-form-urlencoded'となるので、Form Data型でリクエストされる
jQueryのデフォルトも同じ: http://api.jquery.com/jquery.ajax/
ソースはこのようなquerystringになっている

name=jquerypost&hoge=text&...

そして、それ以外のケースに、Request payloadと表記される

まとめると

Content-type
Form Data application/x-www-form-urlencoded
Request Payload multipart/form-data または text/plain

▼Content Type とは?

受取先に「このファイルはこういう形式です」と伝えるヘッダ。
JSONの場合は application/json、フォームデータの場合だとapplication/x-www-form-urlencoded になる。
Payload型だと、サーバ 側でうまくデータの受取ができないことがある。

▼fetch API で、From Data型でリクエストするには?

headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }

を追加するだけ。

これでForm Data型にはなったが、サーバー側に正しい値としては届いていない。
→ bodyに渡すデータをquerystringにする必要がある。

▼Request Payloadで送信してしまった場合、サーバー側で値を取得できるのか

無理やり解析すれば、できる。
詳しくは:http://stackoverflow.com/questions/14525982/getting-request-payload-from-post-request-in-java-servlet
文字列を解析して、jsonにするような処理が必要になるようなので、あまりよくない。

▼まとめ

・POSTリクエストのデータ型はFormDataとRequestPayloadの2種類ある。 ・jQueryAjaxでPOSTリクエストするとき、デフォルトではFormDataになるが、fetch APIだとデフォルトがRequestPayloadになる
・'Content-Type': 'application/x-www-form-urlencoded' とすると、FormData型でリクエストができる
・サーバー側での解析が大変なので基本的にはFormData型で送る方が良いらしい  

▼ちなみに

backbone.jsのajaxもRequest Payloadで送信されてしまうそうです

▼参考URL

http://egapool.hatenablog.com/entry/2015/07/28/225658
http://stackoverflow.com/questions/10494574/what-is-the-difference-between-form-data-and-request-payload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment