🍋
Menu
Troubleshooting Beginner 1 min read 247 words

Troubleshooting CORS Errors in Web Applications

CORS errors are among the most confusing web development issues. Learn how Cross-Origin Resource Sharing works, why browsers block requests, and how to fix common misconfigurations.

Key Takeaways

  • Cross-Origin Resource Sharing is a browser security mechanism that blocks web pages from making requests to domains different from the one serving the page.
  • The server must respond with `Access-Control-Allow-Origin`, `Access-Control-Allow-Methods`, and `Access-Control-Allow-Headers` headers that match the request.
  • "The value of the Access-Control-Allow-Origin header must not be the wildcard '*' when credentials mode is 'include'" — you can't use `*` with cookies; specify the exact origin.

Understanding CORS

Cross-Origin Resource Sharing is a browser security mechanism that blocks web pages from making requests to domains different from the one serving the page. When your frontend at app.example.com calls an API at api.example.com, the browser sends a CORS preflight request to check permissions.

How Preflight Works

For "non-simple" requests (those with custom headers, non-standard methods, or certain content types), the browser sends an OPTIONS request before the actual request. The server must respond with Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers that match the request.

Common Error Patterns

"Access to XMLHttpRequest has been blocked by CORS policy" — the server is not sending the required CORS headers. "The value of the Access-Control-Allow-Origin header must not be the wildcard '*' when credentials mode is 'include'" — you can't use * with cookies; specify the exact origin. "Method PUT is not allowed" — the server's Access-Control-Allow-Methods header doesn't include the HTTP method you're using.

Server-Side Configuration

Return Access-Control-Allow-Origin with the specific requesting origin (not * if cookies are involved). Include all required methods in Access-Control-Allow-Methods. List all custom headers in Access-Control-Allow-Headers. Set Access-Control-Max-Age to cache preflight responses and reduce roundtrips.

Debugging Steps

Use browser DevTools Network tab to inspect both the OPTIONS preflight and the actual request. Check response headers on the preflight — missing or incorrect headers here cause the browser to block the subsequent request. Test with curl to verify the API works outside the browser context (curl doesn't enforce CORS).

相关工具

相关格式

相关指南