English 中文(简体)
How to fix CORS for Capacitor/Quasar App in a Laravel API
原标题:

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,
});
问题回答

Your cors.php config file should look like this:

return [

     paths  => [ api/* ,  sanctum/csrf-cookie ],

     allowed_methods  => [ * ],

     allowed_origins  => [ * ],

     allowed_origins_patterns  => [],

     allowed_headers  => [ * ],

     exposed_headers  => [],

     max_age  => 0,

     supports_credentials  => false, //This can be true or false

];


On your kernel.php file remove IlluminateHttpMiddlewareHandleCors::class, and use FruitcakeCorsHandleCors::class,

Add this "fruitcake/laravel-cors": "^2.0", to your composer.json file, then run composer install

Then, remove some of the header objects on your Axios, and allow Axios to set them for you unless you want to customize them. For instance:

const api = axios.create({
  baseURL: "http://127.0.0.1:8000/api/",
  headers: {
          Authorization: `Bearer ${token}`, //This is optional
          "Content-Type": "application/json",
        },
});


Ensure you restart your laravel local server after doing all this.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签