I've built an AJAX frontend login form, using plain Javascript. It works fine until I try and access it from a different domain.
The problem is CORS and the preflight request. The preflight request doesn't contain the payload from the login form so Craft routes it to a template called 'users/login'. But as the template doesn't exist, the preflight test is returned 'not ok'. CORS looks to be setup okay on the server, because I can get around the problem by creating an empty template for users/login. Then the login form works (preflight test returns ok, so browser proceeds with main request).
What I really need is for the preflight check to not trigger a 404 and return ok, even without the proper payload. Which means Craft not routing that to a template.
Console message without template existing:
Access to XMLHttpRequest at 'http://server.localhost/users/login' from origin 'http://test.localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
General (under headers tab in Chrome):
Request URL: http://server.localhost/users/login
Request Method: OPTIONS
Status Code: 404 Not Found
Remote Address: [::1]:80
Referrer Policy: origin-when-cross-origin
Response header:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-Requested-With, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin: http://test.localhost
Access-Control-Expose-Headers: Content-Security-Policy, Location
Access-Control-Max-Age: 600
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
Date: Tue, 14 Jul 2020 05:49:33 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.41 (Win64) PHP/7.0.33
Transfer-Encoding: chunked
X-Powered-By: Craft CMS
I'm using Wampserver and adding those via .htaccess.
RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L]
Access to XMLHttpRequest at 'http://server.localhost/users/login' from origin 'http://test.localhost' 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.
So it's made things worse. I have the template in there at the moment and it goes through fine until I add your line above.