備忘録

備忘録

FetchAPIを使ってGET/POSTする方法

Ⅰ. はじめに

タイトルの通り「FetchAPIを使ってGET/POSTする方法」です。

Ⅱ. GETする

サンプルプログラム
async function Get() {
  let url = 'https://jsonplaceholder.typicode.com/posts/1';
  let response = await fetch(url);
  // let response = await fetch(url, { credentials: 'include' }); /* cookie を含める場合 */
  let body = await response.text();
  // let body = await response.json();
  console.log(body);
}
実行結果

f:id:kagasu:20171216163634p:plain

Ⅲ. POSTする(JSON)

サンプルプログラム
async function Post() {
  let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'post',
    headers: { 'Content-Type': 'application/json; charset=UTF-8' },
    // credentials: 'include' /* cookie を含める場合 */
    body: JSON.stringify(
    {
      userId: 12345,
      title: 'hi',
      body: 'hello world'
    })
  })
  let body = await response.text();
  // let body = await response.json();
  console.log(body);
}
実行結果

f:id:kagasu:20171216163655p:plain

Ⅳ. POSTする(application/x-www-form-urlencoded)

サンプルプログラム
async function Post() {
  let values = {
     userId: 12345,
     title: 'hi',
     body: 'hello world'
  }

  const urlSearchParams = new URLSearchParams()
  for (const key in values) {
    urlSearchParams.set(key, values[key])
  }

  let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'post',
    body: urlSearchParams
  })
  let body = await response.text()
  console.log(body)
}
実行結果

省略