Build a reusable JavaScript method to perform an AJAX POST request using fetch, sending JSON payloads and handling CSRF tokens when required. The method should validate inputs, set correct headers, and serialize/deserialize JSON safely. It must implement robust error handling for non-2xx responses, network failures, and timeouts, returning a clear, Promise-based result. Include concise documentation and examples so it can be dropped into any project with minimal setup.
Checklist custom field deleted (Define the function signature (e.g., post(url, data, { headers, timeout })) and input validation)
Checklist custom field deleted (Implement fetch with Content-Type: application/json, JSON serialization, and CSRF token injection (if a meta tag or cookie exists))
Checklist custom field deleted (Add error handling: treat non-2xx as errors, parse JSON safely with fallback, implement AbortController timeout, and retry once on network errors)
Checklist custom field deleted (Write unit tests with mocked fetch for success, 4xx/5xx, invalid JSON, timeout, and retry logic; ensure coverage)
Checklist custom field deleted (Document usage and caveats (CORS, CSRF, timeouts), provide example calls, and ensure linter/TypeScript typings if applicable)
Checklist custom fieldDefine function signature and validate input added
Checklist custom fieldImplement fetch with JSON and CSRF added
Checklist custom fieldAdd error handling and retry logic added
Checklist custom fieldWrite unit tests for all cases added
Checklist custom fieldDocument usage, examples, and types added
Checklist custom fieldDefine the function signature (e.g., post(url, data, { headers, timeout })) and input validation added
Checklist custom fieldImplement fetch with Content-Type: application/json, JSON serialization, and CSRF token injection (if a meta tag or cookie exists) added
Checklist custom fieldAdd error handling: treat non-2xx as errors, parse JSON safely with fallback, implement AbortController timeout, and retry once on network errors added
Checklist custom fieldWrite unit tests with mocked fetch for success, 4xx/5xx, invalid JSON, timeout, and retry logic; ensure coverage added
Checklist custom fieldDocument usage and caveats (CORS, CSRF, timeouts), provide example calls, and ensure linter/TypeScript typings if applicable added