I have an API built on CakePHP. It works for the most part but every once in a while browser access to the API dies. The error message on the XHR request response is:
'Access to XMLHttpRequest at 'http://be:8888/api/pings' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
However if I make exactly the same request via POSTMAN (or if I browse directly to the URL, rather than via XHR) it works without any trouble. I thought it might be a pre-flight OPTIONS issue but the request headers don't list a Request Method
and the Apache access log shows these to be GET requests. There's nothing related in the Apache error log.
Restarting MAMP – i.e. Apache – does not fix the issue, nor does flushing the local DNS cache. The only thing that fixes it is a restart, after which it all works fine again for a few hours before eventually going on the blink again.
I can't think of what's causing this. I don't think it's a true CORS middleware error because the restart fixes it and the API is accessible normally. Also if I put a die
in during the CORS middleware __invoke
method it doesn't get that far (the die in the webroot index should be hit first anyway).
I get this error even if I disable the app by putting die('here');
at the start of the webroot index.php file.
Even if I delete the index.php
files (both in the project root and webroot) so that browsing to the URL shows Apache's default error 404 not found: The requested URL /webroot/index.php was not found on this server
, I still get the CORS errors when trying via XHR in the browser.
I've only noticed this issue since upgrading to Mac OS X Catalina.
What could be causing this?
[Update:] Here's proof that it is working in the browser after a system restart:
Summary
URL: http://be:8888/api/clients
Status: 200 OK
Source: Network
Address: ::1.8888
Request
GET /api/clients HTTP/1.1
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
Origin: http://localhost:8080
Accept-Language: en-gb
Access-Control-Allow-Origin: *
Host: be:8888
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate
Connection: keep-alive
However, after a few hours it stops working. If it was actually a CORS issue my understanding is that it would NEVER work.