Why does my http://localhost CORS origin not work?
To quickly solve CORS issues with localhost, add a response header Access-Control-Allow-Origin: * to allow any origin, or "http://localhost:PORT" to allow a specific origin. Here's an Express.js, Node.js snippet:
Replace PORT with your client’s actual port. For production, restrict the origin to secure your application.
Overcoming Chrome and its restrictions
Chrome poses some challenges with CORS when using localhost. One workaround is substituting the domain localhost with localho.st, which points to IP 127.0.0.1.
For testing in Chrome, you could disable web security temporarily.
Mind you, this is the equivalent of walking into a zombie apocalypse with a vaseline shield.
Developer-friendly Chrome extension
Use a Chrome extension for testing, such as "Allow-Control-Allow-Origin: *", which adds CORS headers as needed.
Warning: Remember that this is a temporary measure and can be a certain recipe for disaster when used in production.
Server setup: Getting it right
If your server response lacks the correct Access-Control-Allow-Origin header, http://localhost won't be permitted:
You can extend the Chrome CORS Extension for more granular control using source code available on GitHub.
Client-side Capers
CORS errors could also be a result of the client script. For instance, when using XMLHttpRequest, you might encounter CORS restrictions:
Embrace the power of proxy
local-cors-proxy offers a simplified solution to bypass CORS restrictions. Install it via npm and create a proxy server:
Update your client script to point at the proxy:
Handling Preflight Lift-off
For certain requests, browsers perform a preflight request using the OPTIONS method. Here's how you can handle it:
Dynamic Origins and validation
In scenarios where CORS origins can't be hardcoded, validate the HTTP_ORIGIN against a list of allowed domains:
PHP: Handling Preflight the Right way
Always end your preflight handling script in PHP with exit(0)
Was this article helpful?