JavaScript

Fetch API まとめ

Can I use…​ Fetch

A modern replacement for XMLHttpRequest.

window.fetch polyfill

$ npm install whatwg-fetch --save
import 'whatwg-fetch'

Response

HTML

fetch('/users.html')
  .then((res) => {
    return res.text()
  }).then((body) => {
    document.body.innerHTML = body
  })

JSON

fetch('/users.json')
  .then((res) => {
    return res.json()
  }).then((json) => {
    console.log('success:', json)
  }).catch((ex) => {
    console.log('failed:', ex)
  })

Response metadata

fetch('/users.json').then((res) => {
  console.log('Content-Type', res.headers.get('Content-Type'))
  console.log('Date', res.headers.get('Date'))
  console.log('status', res.status)
  console.log('statusText', res.statusText)
})

POST Form Data

const form = document.querySelector('form')

fetch('/users', {
  method: 'POST',
  body: new FormData(form),
})
const fd = new FormData(form)
fd.append('foo', 'bar')

fetch('/users', {
  method: 'POST',
  body: fd,
})

POST :: jQuery と fetch API の違い

jQuery

Form Data

fetch API

Request Payload

fetch API にて Form Data でリクエストするには Content-Type を指定する

headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
fetch API - POST example
import queryString from 'query-string';

fetch('https://example.com', {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
  method: 'POST',
  body: queryString.stringify(this.query),
}).then(res => res.json()).then((json) => {
  console.log(json);
}).catch((ex) => {
  console.warn(ex);
});

DELETE

DELETE メソッドは GET と同様に payload body を持てないため、 POST の例で示したようなリクエストを投げると 400 Bad Request となる。

DELETE is not supposed to have a body, just like GET.
fetch(url, {
  credentials: 'include',
})

curl

POST application/x-www-form-urlencoded

default:

curl -d "param1=value1&param2=value2" -X POST http://localhost:3000/data

explicit:

curl -d "param1=value1&param2=value2" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:3000/data

with a data file

curl -d "@data.txt" -X POST http://localhost:3000/data

POST application/json

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data

with a data file

curl -d "@data.json" -X POST http://localhost:3000/data