Introduction
fetch() requests a resource over HTTP and returns a promise for the response.
- Using Fetch (developer.mozilla.org)
- fetch() (developer.mozilla.org)
Fetch
fetch('/data.json')
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(err => ...)
See: fetch() (developer.mozilla.org)
Response
fetch('/data.json')
.then(res => {
res.text() // response body (=> Promise)
res.json() // parse via JSON (=> Promise)
res.status //=> 200
res.statusText //=> 'OK'
res.redirected //=> false
res.ok //=> true
res.url //=> 'http://site.com/data.json'
res.type //=> 'basic'
// ('cors' 'default' 'error'
// 'opaque' 'opaqueredirect')
res.headers.get('Content-Type')
})
See: Response, Response.type (developer.mozilla.org)
Request options
fetch('/data.json', {
method: 'post',
body: new FormData(form), // post body
body: JSON.stringify(...),
headers: {
'Accept': 'application/json'
},
credentials: 'same-origin', // send cookies
credentials: 'include', // send cookies, even in CORS
credentials: 'omit', // never send cookies
})
See: Request, Request.credentials (developer.mozilla.org)
Catching errors
fetch('/data.json')
.then(checkStatus)
function checkStatus (res) {
if (res.status >= 200 && res.status < 300) {
return res
} else {
let err = new Error(res.statusText)
err.response = res
throw err
}
}
fetch() rejects only on network errors; check res.ok yourself.
See: Response.ok (developer.mozilla.org)
Node.js
const res = await fetch('https://example.com/data.json')
Node 18+ has a global fetch (stable in Node 21). On older versions, use
undici or
node-fetch.
See: fetch() (developer.mozilla.org)
0 Comments for this cheatsheet. Write yours!