惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
C
Check Point Blog
博客园 - Franky
月光博客
月光博客
T
Tenable Blog
博客园 - 聂微东
Cyberwarzone
Cyberwarzone
The GitHub Blog
The GitHub Blog
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
IT之家
IT之家
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
CXSECURITY Database RSS Feed - CXSecurity.com
F
Full Disclosure
博客园 - 司徒正美
Project Zero
Project Zero
Y
Y Combinator Blog
A
Arctic Wolf
美团技术团队
博客园 - 叶小钗
S
Securelist
F
Fortinet All Blogs
T
Threatpost
T
Threat Research - Cisco Blogs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
酷 壳 – CoolShell
酷 壳 – CoolShell
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
Recorded Future
Recorded Future
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Schneier on Security
Apple Machine Learning Research
Apple Machine Learning Research
L
LangChain Blog
P
Privacy International News Feed
博客园_首页
S
SegmentFault 最新的问题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
P
Proofpoint News Feed
Cisco Talos Blog
Cisco Talos Blog
AWS News Blog
AWS News Blog
阮一峰的网络日志
阮一峰的网络日志
G
Google Developers Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
雷峰网
雷峰网
P
Proofpoint News Feed
Latest news
Latest news
G
GRAHAM CLULEY

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Replace axios with a simple custom fetch wrapper
Kent C. Dodds 🏹 @kentcdodds · 2020-03-30 · via Kent C. Dodds Blog

I remember being with Matt Zabriskie when he hatched the idea of a vanilla JavaScript version of AngularJS's $http service. It seemed like a brilliant idea and that night in his hotel room at MidwestJS, he put together the first iteration.

It was awesome because working with raw XMLHttpRequest to make HTTP requests was not very fun. His library, which he later called axios is a brilliant work and functioned both in NodeJS and the Browser which I remember him being really excited about (and I was too).

It's been almost six years now and if you're reading this chances are you've at least heard of it and very likely used it in the past or are using it now. It has an enormous and growing number of downloads on npm. And while Matt's long moved on from the project, it is still actively maintained.

Since it was released, the browser standard has evolved to add a new, promise-based API for making HTTP requests that provided a much nicer developer experience. This API is called fetch and if you haven't used it yet, you really ought to check it out. It's widely supported and easily polyfillable (my favorite is unfetch because the dog mascot is cute 🐶).

Here are a few reasons you might consider swapping axios for a simple custom wrapper around fetch:

  1. Less API to learn
  2. Smaller bundle size
  3. Reduced trouble when updating packages/managing breaking changes
  4. Immediate bug fixes/releases
  5. Conceptually simpler

I have a fetch wrapper for my bookshelf app which has served me well. Let's build it together:

function client(endpoint, customConfig) {
	const config = {
		method: 'GET',
		...customConfig,
	}

	return window
		.fetch(`${process.env.REACT_APP_API_URL}/${endpoint}`, config)
		.then((response) => response.json())
}

This client function allows me to make calls to my app's API like so:

client(`books?query=${encodeURIComponent(query)}`).then(
	(data) => {
		console.log('here are the books', data.books)
	},
	(error) => {
		console.error('oh no, an error happened', error)
	},
)

However, the built-in window.fetch API doesn't handle errors in the same way axios does. By default, window.fetch will only reject a promise if the actual request itself failed (network error), not if it returned a "Client error response". Luckily, the Response object has an ok property which we can use to reject the promise in our wrapper:

function client(endpoint, customConfig = {}) {
	const config = {
		method: 'GET',
		...customConfig,
	}

	return window
		.fetch(`${process.env.REACT_APP_API_URL}/${endpoint}`, config)
		.then(async (response) => {
			if (response.ok) {
				return await response.json()
			} else {
				const errorMessage = await response.text()
				return Promise.reject(new Error(errorMessage))
			}
		})
}

Great, now our promise chain will reject if the response is not ok.

The next thing we want to do is be able to send data to the backend. We can do this with our current API, but let's make it easier:

function client(endpoint, { body, ...customConfig } = {}) {
	const headers = { 'Content-Type': 'application/json' }
	const config = {
		method: body ? 'POST' : 'GET',
		...customConfig,
		headers: {
			...headers,
			...customConfig.headers,
		},
	}
	if (body) {
		config.body = JSON.stringify(body)
	}

	return window
		.fetch(`${process.env.REACT_APP_API_URL}/${endpoint}`, config)
		.then(async (response) => {
			if (response.ok) {
				return await response.json()
			} else {
				const errorMessage = await response.text()
				return Promise.reject(new Error(errorMessage))
			}
		})
}

Sweet, so now we can do stuff like this:

client('login', { body: { username, password } }).then(
	(data) => {
		console.log('here the logged in user data', data)
	},
	(error) => {
		console.error('oh no, login failed', error)
	},
)

Next we want to be able to make authenticated requests. There are various approaches for doing this, but here's how I do it in the bookshelf app:

const localStorageKey = '__bookshelf_token__'

function client(endpoint, { body, ...customConfig } = {}) {
	const token = window.localStorage.getItem(localStorageKey)
	const headers = { 'Content-Type': 'application/json' }
	if (token) {
		headers.Authorization = `Bearer ${token}`
	}
	const config = {
		method: body ? 'POST' : 'GET',
		...customConfig,
		headers: {
			...headers,
			...customConfig.headers,
		},
	}
	if (body) {
		config.body = JSON.stringify(body)
	}

	return window
		.fetch(`${process.env.REACT_APP_API_URL}/${endpoint}`, config)
		.then(async (response) => {
			if (response.ok) {
				return await response.json()
			} else {
				const errorMessage = await response.text()
				return Promise.reject(new Error(errorMessage))
			}
		})
}

So basically if we have a token in localStorage by that key, then we add the Authorization header (per the JWT spec) which our server can then use to determine whether the user is authorized. Very common practice there.

Another handy thing that we can do is if the response.status is 401, that means the user's token is invalid (maybe it expired or something) so we can automatically log the user out and refresh the page for them:

const localStorageKey = '__bookshelf_token__'

function client(endpoint, { body, ...customConfig } = {}) {
	const token = window.localStorage.getItem(localStorageKey)
	const headers = { 'content-type': 'application/json' }
	if (token) {
		headers.Authorization = `Bearer ${token}`
	}
	const config = {
		method: body ? 'POST' : 'GET',
		...customConfig,
		headers: {
			...headers,
			...customConfig.headers,
		},
	}
	if (body) {
		config.body = JSON.stringify(body)
	}

	return window
		.fetch(`${process.env.REACT_APP_API_URL}/${endpoint}`, config)
		.then(async (response) => {
			if (response.status === 401) {
				logout()
				window.location.assign(window.location)
				return
			}
			if (response.ok) {
				return await response.json()
			} else {
				const errorMessage = await response.text()
				return Promise.reject(new Error(errorMessage))
			}
		})
}

function logout() {
	window.localStorage.removeItem(localStorageKey)
}

Depending on your situation, maybe you'd re-route them to the login screen instead.

On top of this, the bookshelf app has a few other wrappers for making requests. Like the list-items-client.js:

import { client } from './api-client'

function create(listItemData) {
	return client('list-items', { body: listItemData })
}

function read() {
	return client('list-items')
}

function update(listItemId, updates) {
	return client(`list-items/${listItemId}`, {
		method: 'PUT',
		body: updates,
	})
}

function remove(listItemId) {
	return client(`list-items/${listItemId}`, { method: 'DELETE' })
}

export { create, read, remove, update }

Conclusion

Axios does a LOT for you and if you're happy with it then feel free to keep using it (I use it for node projects because it's just great and I haven't been motivated to investigate the alternatives that I'm sure you're dying to tell me all about right now). But for the browser, I think that you'll often be better off making your own simple wrapper around fetch that does exactly what you need it to do and no more. Anything you can think of for an axios interceptor or transform to do, you can make your wrapper do it. If you don't want it applied to all requests, then you can make a wrapper for your wrapper.

Good luck!