在TypeScript中,发送我们可以使用fetch函数来发送HTTP请求,请求以下是发送一个(ge)简单的示例:(图片来源网络,侵删)
// 定义一个接口,请求用于描述API的发送响应数据结构interface ApiResponse { data: any; status: number;}// 定义一个函数,用于发送GET请求async function getRequest(url: string): Promise<ApiResponse> { const response = await fetch(url); const data = await response.json(); return { data,请求 status: response.status, };}// 定义一个函数(shu),用于发送POST请求async function postRequest(url: string,发送 body: any): Promise<ApiResponse> { const response = await fetch(url, { method: 'POST', headers: { 'ContentType': 'application/json', }, body: JSON.stringify(body), }); const data = await response.json(); return { data, status: response.status, };}// 使用示例(async () => { const url = 'https://api.example.com/data'; // 发送GET请求 const getResponse = await getRequest(url); console.log('GET请求响应:', getResponse); // 发送POST请求 const postBody = { key: 'value' }; const postResponse = await postRequest(url, postBody); console.log('POST请求响应:', postResponse);})();在这个示例中,我们首先(xian)定义了一个接口ApiResponse,请求用于描述API的发送响应数(shu)据结构,我们定义了两个函数getRequest和postRequest,请求分(fen)别用(yong)于发送GET和POST请求,发送这两个函数都返回一个Promise,请求当请求完成时,发送Promise会(hui)解析为一个包含响(xiang)应数据(ju)和状态码的请求对象。

我们展示了如何使用这两个函数发送请求,发送我们首先调(diao)用getRequest函数发送一个GET请求,然后调用postRequest函数发送一个POST请求,每次请求完成后,我(wo)们都将(jiang)响(xiang)应数(shu)据打印到控制台。

(作者:APP开发)