I have an App built on top of Quasar and Capacitor, with an API built on top of Laravel. Everything works well on the dev environment until I build and install the app on my phone, then I keep getting timeouts, decided to build a SPA and run it with Liteserver and it turns out that the server was returning an: "Access to XMLHttpRequest at https://smk.toneflix.com.ng/api/pages/about from origin http://localhost:3000 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.
" error.
On my Kernel.php I do have this:
protected $middleware = [
// AppHttpMiddlewareTrustHosts::class,
AppHttpMiddlewareTrustProxies::class,
IlluminateHttpMiddlewareHandleCors::class,
AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
];
And on my cors.php config file, I also have this:
return [
paths => [ * ],
allowed_methods => [ * ],
allowed_origins => [ * ],
allowed_origins_patterns => [],
allowed_headers => [ * ],
exposed_headers => [],
max_age => 0,
supports_credentials => true,
];
I also have this in my sanctum.php config
return [
stateful => explode( , , env( SANCTUM_STATEFUL_DOMAINS , sprintf(
%s%s ,
localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1 ,
Sanctum::currentApplicationUrlWithPort(),
env( APP_URL ) ? , .parse_url(env( APP_URL ), PHP_URL_HOST) : ,
env( FRONTEND_URL ) ? , .parse_url(env( FRONTEND_URL ), PHP_URL_HOST) :
))),
...
]
I ve tried several other configuration options, and suggestions from other SO answers, but non is helping. Everything works in Postman and if I create a subdomain on the API domain and host an SPA, but that is not what I want, I need requests to go through on the native app when running on a real device.
EDIT
I figured out that my device makes requests from https://localhost
, so I added that to the FRONTEND_URL
Environment variable, and it worked, but I do understand that this is not sustainable given that I do not have control over where my apps will run, so I don t consider that to be a fix.
FOR CONTEXT
Here is my default axios setup:
let headers = {
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"Access-Control-Allow-Credentials": "true",
"Content-Type": "application/json; charset=utf-8",
"X-Requested-With": "XMLHttpRequest",
"SameSite": "None",
};
axios.defaults.withCredentials = true;
const api = axios.create({
baseURL: "http://127.0.0.1:8000/api/",
headers,
});