Preface
Axios is a promise-based HTTP client for browsers and . Secondary encapsulation Axios is mainly used to manage HTTP requests in a unified manner, such as setting a unified request prefix, header, timeout time, uniformly handling requests and responses, and error handling.
The following is a detailed scenario use case for Axios secondary encapsulation using TypeScript:
1. Create an Axios instance
First, create an Axios instance and configure common parameters.
import axios from 'axios'; const instance = ({ baseURL: '', timeout: 10000, // Request timeout headers: {'Content-Type': 'application/json'} }); export default instance;
2. Unified request processing
Encapsulation of request methods, including unified request prefix, header processing, etc.
// import axios from './path/to/axiosInstance'; // Add a common request prefixfunction request(url: string, config?: AxiosRequestConfig) { const fullPath = `/api/${url}`; // You can add a common header or other configuration here const defaultConfig = { headers: { 'Authorization': `Bearer ${('token')}` } }; return axios({ url: fullPath, ...config, ...defaultConfig }); } export default request;
3. Response Interceptor
Process response interceptors and uniformly process response data formats.
// (Continue with the above code)import axios, { AxiosInstance } from 'axios'; // Response Interceptor(response => { // Do something about the response data return ; }, error => { // Do something to respond to errors return (error); }); export default instance;
4. Error handling
Unified HTTP request errors.
// (Continue with the above code)import { AxiosError } from 'axios'; // Use encapsulated request functionfunction handleError(error: AxiosError) { if () { // The request has been issued, and the server responds to other statuses other than status code 2xx (); (); (); } else if () { // The request has been issued but no response has been received (); } else { // An issue occurred that triggered the request error ('Error', ); } return (error); } export { handleError };
5. Use encapsulated HTTP client
Use an encapsulated HTTP client to make requests in components or other services.
// import http from './path/to/http'; import { handleError } from './path/to/http'; export default { async created() { try { const response = await http('/user', { method: 'get' }); = ; } catch (error) { handleError(error); } } };
6. Encapsulate specific API requests
Create specific API service files, such as user services.
// api/ import http from '../http'; export const getUser = (userId: string) => http(`/users/${userId}`); export const updateUser = (userId: string, userData: object) => http(`/users/${userId}`, { method: 'put', data: userData }); // Other API calls...
7. Use specific API services
Use specific API services in components.
// import { getUser, updateUser } from './api/user'; export default { methods: { async fetchUser() { try { const user = await getUser('123'); = user; } catch (error) { handleError(error); } }, async saveUser() { try { await updateUser('123', { name: 'New Name' }); } catch (error) { handleError(error); } } } };
Through the above steps, you can create a maintainable, easy-to-use HTTP client that includes unified configuration, interceptors, error handling, and API call encapsulation. This makes it more consistent and convenient to make API requests in your project.
Summarize
This is the article about the use cases of using Axios combined with Typescript secondary packaging. This is all about this article. For more related content related to Axios combined with Typescript secondary packaging, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!