寻求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
TypeErrorinstances which occur when the request can't be completed (e.g., no internet connection, CORS restrictions, invalid URL). - HTTP Error Codes: Explicitly checks
response.okto handle 4xx (client errors) and 5xx (server errors) statuses, which the nativefetchAPI 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
AbortControllerto cancel requests that take too long (uncomment thesignalline 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
相关产品推荐
相关产品推荐

