You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求TypeScript中带JSON参数的REST API POST请求示例

TypeScript POST Request with JSON Payload & Comprehensive Error Handling

Got it, here's a robust TypeScript example that covers sending a POST request with JSON parameters, parsing the response, and handling all common error scenarios you're likely to encounter:

// Define TypeScript interfaces for type safety
interface RequestPayload {
  username: string;
  email: string;
  password: string;
}

interface ApiResponse {
  id: string;
  message: string;
  userData: {
    username: string;
    email: string;
  };
}

async function sendPostRequest(url: string, payload: RequestPayload): Promise<ApiResponse> {
  try {
    // Configure and send the POST request
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // Add any additional headers here (e.g., Authorization)
      },
      body: JSON.stringify(payload),
      // Optional: Uncomment below for timeout handling
      // signal: abortController.signal
    });

    // Handle HTTP error codes (fetch doesn't reject on 4xx/5xx statuses)
    if (!response.ok) {
      // Extract error details from the response if available
      let errorDetails: string | undefined;
      try {
        errorDetails = await response.text();
      } catch {}

      throw new Error(`HTTP error! Status: ${response.status} - ${response.statusText}\nDetails: ${errorDetails || 'No additional details'}`);
    }

    // Parse JSON response
    try {
      const data: ApiResponse = await response.json();
      return data;
    } catch (parseError) {
      throw new Error(`Failed to parse response as JSON: ${(parseError as Error).message}`);
    }

  } catch (error) {
    // Handle different error types
    if (error instanceof TypeError) {
      // Network errors (e.g., no internet, CORS issues)
      throw new Error(`Network error occurred: ${error.message}`);
    } else if (error instanceof Error) {
      // Re-throw HTTP/parsing errors we already wrapped
      throw error;
    } else {
      // Catch-all for unexpected error types
      throw new Error(`Unexpected error: ${String(error)}`);
    }
  }
}

// Example usage
async function main() {
  try {
    const payload: RequestPayload = {
      username: 'john_doe',
      email: 'john@example.com',
      password: 'secure123'
    };

    const response = await sendPostRequest('https://api.example.com/register', payload);
    console.log('Request successful:', response);
  } catch (error) {
    if (error instanceof Error) {
      console.error('Request failed:', error.message);
      // Add business logic for specific errors here
      // e.g., if (error.message.includes('401')) { redirectToLogin() }
    }
  }
}

main();

Key Details & Error Scenarios Handled:

  • Type Safety: Uses TypeScript interfaces to enforce the structure of both the request payload and response data, catching mismatches at compile time.
  • Network Errors: Catches TypeError instances which occur when the request can't be completed (e.g., no internet connection, CORS restrictions, invalid URL).
  • HTTP Error Codes: Explicitly checks response.ok to handle 4xx (client errors) and 5xx (server errors) statuses, which the native fetch API doesn't automatically reject.
  • JSON Parsing Failures: Wraps the response.json() call in a try-catch to handle cases where the API returns non-JSON data (e.g., plain text error messages).
  • Catch-All Error Handling: Provides a fallback for unexpected error types to ensure no scenario is unhandled.

Bonus Tips for Production:

  • Add Timeout Handling: Use AbortController to cancel requests that take too long (uncomment the signal line in the fetch config and set up a timeout).
  • Reusable Base Client: Extract common headers, base URL, and error handling into a reusable API client class to avoid code duplication.
  • Error Code Specific Logic: In the catch block of your usage code, check for specific status codes (e.g., 401 for unauthorized, 404 for not found) to trigger appropriate user-facing actions.

内容的提问来源于stack exchange,提问作者waterscorpio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:24:52