Last active
March 10, 2025 21:50
-
-
Save JaysonChiang/fa704307bacffe0f17d51acf6b1292fc to your computer and use it in GitHub Desktop.
Example of Axios with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios, { AxiosError, AxiosResponse } from 'axios'; | |
import token from './somewhere'; | |
interface Todo { | |
id: string; | |
title: string; | |
} | |
interface User { | |
id: string; | |
name: string; | |
} | |
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com'; | |
axios.interceptors.request.use((config) => { | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}); | |
axios.interceptors.response.use( | |
(res) => res, | |
(error: AxiosError) => { | |
const { data, status, config } = error.response!; | |
switch (status) { | |
case 400: | |
console.error(data); | |
break; | |
case 401: | |
console.error('unauthorised'); | |
break; | |
case 404: | |
console.error('/not-found'); | |
break; | |
case 500: | |
console.error('/server-error'); | |
break; | |
} | |
return Promise.reject(error); | |
} | |
); | |
const responseBody = <T>(response: AxiosResponse<T>) => response.data; | |
const request = { | |
get: <T>(url: string) => axios.get<T>(url).then(responseBody), | |
post: <T>(url: string, body: {}) => | |
axios.post<T>(url, body).then(responseBody), | |
}; | |
const todos = { | |
list: () => request.get<Todo[]>('/todos'), | |
details: (id: string) => request.get<Todo>(`/todos/${id}`), | |
create: (data: Todo) => request.post<void>('/todos', data), | |
}; | |
const users = { | |
list: () => request.get<User[]>('/users'), | |
details: (id: string) => request.get<User>(`/users/${id}`), | |
create: (data: User) => request.post<User>('/users', data), | |
}; | |
const api = { | |
todos, | |
users, | |
}; | |
export default api; |
@JaysonChiang : Can you please give us some more information how to use this script ?
How can I "run" this (e.g. on port 3000), so I can use it with postman ?
Thanks in advance for your reply.
@jdriesen This is an example of using axios library.
interceptors.request is used to add to each request a Auth header with token. It's part of JWT auth.
interseptors.response is used to handle error if some exist after each request.
After there is some fetch examples. Then in code U can call, for example, api.users.list to call get requset that fetches all users
U can not run this and use this with postman 'cause it's implementation of frontend side.
great! Thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks man. This will help me understand.