You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Quasar+Capacitor应用对接Laravel API的CORS问题

Quasar+Capacitor 原生应用请求 Laravel API 超时/跨域问题排查记录

问题背景

基于 Quasar 和 Capacitor 开发的原生应用,后端 API 使用 Laravel 构建。开发环境下功能一切正常,但将应用打包安装到手机后,请求 API 持续出现超时问题。将应用构建为 SPA 并用 Liteserver 运行时,明确收到 CORS 错误提示:

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.

现有配置详情

Kernel.php 中间件配置

protected $middleware = [
    // \App\Http\Middleware\TrustHosts::class,
    \App\Http\Middleware\TrustProxies::class,
    \Illuminate\Http\Middleware\HandleCors::class,
    \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

cors.php 跨域配置

return [
    'paths' => ['*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

sanctum.php 相关配置

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) : ''
    ))),
    ...
]

Axios 默认请求配置

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,
});

排查经过

  • Postman 直接请求 API 完全正常,在 API 域名下部署子域名 SPA 也能正常运行,但原生设备端请求始终异常。
  • 发现测试设备的请求来源为 https://localhost,将其加入 FRONTEND_URL 环境变量后问题暂时解决,但该方案不可持续,无法适配所有运行环境。
  • 求助社区后,通过远程协作排查,曾推测可能是服务器问题,但开发环境访问线上 API 一切正常,该方向排除。

最终结论

耗时3天排查,确认所有后端配置均无问题,异常原因是测试手机自身存在未知故障。在 Appetize 平台运行应用时,所有功能表现完全正常。

内容的提问来源于stack exchange,提问作者3m1n3nc3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:43:24