在TypeScript中,發(fā)送我們可以使用fetch函數來(lái)發(fā)送HTTP請求,請求以下是發(fā)送一個(gè)簡(jiǎn)單的示例:
// 定義一個(gè)接口,請求用于描述API的發(fā)送響應數據??結(╯‵□′)╯構interface ApiResponse { data: any; status: number;}// 定義一個(gè)函(╯°□°)╯數,用于發(fā)送GET請求async function getRequest??(url: string): Promise<ApiR(╯‵□′)╯es??ponse> { const resp(′▽?zhuān)?onse = await fetch(url); const data = awa??it response.json(); return { data,請求(′▽?zhuān)? status: response.status, };}// 定義一個(gè)函數,用于發(fā)送POST請求async function postRequest((′?_?`)url: string,發(fā)送 body: any): Promise<??ApiResponse> { const response = await fetch(url, { method: 'POST', headers: { 'ContentType': 'a??pplication/ヾ(′?`)?json', }, body: JSON.stringify(body), }); const da???ta = await response.json(); return { data, sta┐(′?`)┌tus: res??ponse.status, };}// 使用示例(async () => { const url = 'https://api.example.com/data'; // 發(fā)送GE??T請求 const getResponse = await getRequest(url); console.log('GET請求響應:', getResponse); // 發(fā)送POST請求 const postBo(╬?益?)dy = { key: 'value' }; const postResponse = await post(′▽?zhuān)?)Request(url, postBody); console.log('POST請求響應:', postResponse);})();在這個(gè)示例中,我們首先定義了一個(gè)接口ApiResponse,請求用于描述API的發(fā)送響應數據結構,我們定義了兩個(gè)函數getRequest和postRequest,請求分別用于發(fā)送GET和POST請求,發(fā)送這兩個(gè)函??數都返回一個(gè)Promise,請求當請求完成時(shí),發(fā)送Promise會(huì )解析為一個(gè)包含響應數據和狀態(tài)碼的請求對象。
我們展示了如何使用這兩個(gè)函數發(fā)送請求,發(fā)送我們首先調用getRequest函數發(fā)送一個(gè)GET請求,然后調用postReq???uest函數ヽ(′▽?zhuān)?ノ發(fā)送一個(gè)POST請求,每次請求完成后,我們都將響應數據打印到控制臺。
(作者:AI運營(yíng)推廣)