Skip to content

Conversation

@ovcrash
Copy link

@ovcrash ovcrash commented Dec 11, 2025

Problem

When running the Hashtopolis frontend and backend on different ports (e.g., frontend on :4200, backend on :8080), browsers block API requests with CORS errors:

Access to XMLHttpRequest at '[http://host:8080/api/v2/auth/token](vscode-file://vscode-app/c:/Program%20Files/Microsoft%20VS%20Code/resources/app/out/vs/code/electron-browser/workbench/workbench.html)' from origin '[http://host:4200](vscode-file://vscode-app/c:/Program%20Files/Microsoft%20VS%20Code/resources/app/out/vs/code/electron-browser/workbench/workbench.html)'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

The CorsHackMiddleware was failing for cross-origin requests because OPTIONS preflight requests don't match any defined route. The middleware attempted to get RouteContext before handling the preflight, causing the request to fail without CORS headers.

Root Cause

The CorsHackMiddleware in src/api/v2/index.php attempts to get RouteContext for every request. However, OPTIONS preflight requests don't match any defined route, causing the middleware to fail before CORS headers can be added.

Solution

  • Handle OPTIONS preflight requests immediately, returning proper CORS headers without attempting to route them
  • Add try/catch around RouteContext to gracefully handle edge cases
  • Add Access-Control-Max-Age header to allow browsers to cache preflight responses
  • Improved code documentation

Testing

Tested with:

  • Frontend running on http://10.2.3.4:4200
  • Backend running on http://10.2.3.4:8080
  • Cross-origin requests now work correctly

Changes:

  • Handle OPTIONS requests immediately, returning proper CORS headers
  • Add try/catch for RouteContext to gracefully handle edge cases
  • Add Access-Control-Max-Age header for preflight caching
  • Improve code documentation

This fixes CORS errors when running frontend and backend on different ports (e.g., frontend on :4200, backend on :8080).

The CorsHackMiddleware was failing for cross-origin requests because
OPTIONS preflight requests don't match any defined route. The middleware
attempted to get RouteContext before handling the preflight, causing
the request to fail without CORS headers.

Changes:
- Handle OPTIONS requests immediately, returning proper CORS headers
- Add try/catch for RouteContext to gracefully handle edge cases
- Add Access-Control-Max-Age header for preflight caching
- Improve code documentation

This fixes CORS errors when running frontend and backend on different
ports (e.g., frontend on :4200, backend on :8080).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant