在 TypeScript 中,可以使用 axiosfetch 等 HTTP 客戶端庫來進行請求。以下是使用 axios 封裝三個請求的方法的示例:

  1. GET 請求:
import axios, { AxiosResponse } from 'axios';

async function getRequest(url: string): Promise<AxiosResponse> {
  try {
    const response = await axios.get(url);
    return response;
  } catch (error) {
    throw new Error(error);
  }
}
  1. POST 請求:
import axios, { AxiosResponse } from 'axios';

async function postRequest(url: string, data: any): Promise<AxiosResponse> {
  try {
    const response = await axios.post(url, data);
    return response;
  } catch (error) {
    throw new Error(error);
  }
}
  1. PUT 請求:
import axios, { AxiosResponse } from 'axios';

async function putRequest(url: string, data: any): Promise<AxiosResponse> {
  try {
    const response = await axios.put(url, data);
    return response;
  } catch (error) {
    throw new Error(error);
  }
}

這些方法可以根據需要進行修改和擴展,例如添加錯誤處理、標頭設置、取消請求等。請注意,上述代碼中使用了 async/awaitPromise,這是因為 axios 的請求方法返回的是一個 Promise 對象

typescript 封裝三個請求的方法

原文地址: https://www.cveoy.top/t/topic/izh9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录