4 Common Mistakes Front End Developers Make When Using `fetch`

Cameron Nokes
Jan 9, 2018 · 3 min read
I felt obligated to make the Mean Girls reference

1. Assuming that the promise rejects on HTTP error statuses

Fetch is promise based, so it’s easy to assume that it will reject it’s promise if it receives an HTTP error status, like 404 or 500. Just like raw XMLHttpRequest, that’s not the case with fetch — it only rejects it’s promise on a “network error” (sort of a confusing term, but that’s what the spec says). If you get an http error from a server, the server is working and actively processing requests, so a network error represents when the server can’t be reached at all (e.g connection refused or name not resolved) or there’s an error with the request configuration, for example.

fetch('ftp://example.com')
.catch(err => console.error('Caught error: ', err))
fetch('https://jsonplaceholder.typicode.com/404')
.then(res => console.log('response: ', res))
.catch(console.error)
fetch('https://jsonplaceholder.typicode.com/404')
.then(res => {
if(res.ok) {
return res;
} else {
throw Error(`Request rejected with status ${res.status}`);
}
})
.catch(console.error)

2. Forgetting to include credentials

Unlike XHR, fetch does not include any cookies in the request by default. So if requests against your API require cookie based authorization (most web apps do) this has to be there or your call will likely return 401 Unauthorized.

fetch('/url', { credentials: 'include' })

3. Forgetting to set the `Content-Type` to `application/json` when POSTing JSON

$http, axios, and others tend to default to setting this header for you, so it’s easy to forget.

fetch('https://cameronnokes.com/slack-ron-swanson-quote-bot/ron', { 
method: 'POST',
body: JSON.stringify({text: 'bacon'}),
headers: {'Content-Type': 'application/json'}
})
.then(res => res.json())
.then(console.log)

4. Manually writing out complicated query params in a string

I’ve seen code like this:

fetch('/endpoint?foo=${n > 1 ? 123 : 456}&bar=abc&query=${encodeURIComponent(someString || '')}

Conclusion

Fetch is awesome but enjoy responsibly :)


If you enjoy tweets about JavaScript (you know you do), you can follow me here https://twitter.com/ccnokes.

Cameron Nokes

Javascript and front-end development how-tos

Cameron Nokes

Written by

Front-end developer and hamburger eater. Check out my screencasts: https://egghead.io/instructors/cameron-nokes

Cameron Nokes

Javascript and front-end development how-tos