Fix CORS preflight OPTIONS request handling #1831
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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: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
CorsHackMiddlewareinsrc/api/v2/index.phpattempts to getRouteContextfor every request. However,OPTIONSpreflight requests don't match any defined route, causing the middleware to fail before CORS headers can be added.Solution
OPTIONSpreflight requests immediately, returning proper CORS headers without attempting to route themRouteContextto gracefully handle edge casesAccess-Control-Max-Ageheader to allow browsers to cache preflight responsesTesting
Tested with:
http://10.2.3.4:4200http://10.2.3.4:8080Changes:
This fixes CORS errors when running frontend and backend on different ports (e.g., frontend on :4200, backend on :8080).