【问题标题】:Cordova app throws a CORS error when connecting to a production APICordova 应用程序在连接到生产 API 时引发 CORS 错误
【发布时间】:2023-04-05 05:16:02
【问题描述】:

我在本地环境中有我的应用程序,并尝试在 Hostinger 上测试我新部署的后端 api (Laravel),当尝试与之连接时,它会引发 CORS 错误。 这是我的网络选项卡上的示例日志:

问:如果我构建 APK,会发生这种情况吗?我该如何解决这个问题?

这是我的应用程序的 .env 文件

VUE_APP_NAME="SSIS"
VUE_APP_API_URL=https://psussis-online.preview-domain.com
VUE_APP_APP_VERSION=2.0.0
VUE_APP_API_KEY="HWmxFAQajmY="

这是我部署的后端的 .htacess 文件

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

【问题讨论】:

    标签: laravel vue.js cordova cors


    【解决方案1】:

    首先创建一个中间件名称cors并在kernel.php上注册。 然后在路由组上添加这个中间件到 routes/api.php。

    中间件代码是-

    public function handle($request, Closure $next)
    {
    
        header("Access-Control-Allow-Origin: *");
    
        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Origin', '*',
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }
    
        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }
    

    现在在 routes/api.php

     Route::group(['middleware' => 'cors'], function (){//your routes});
    

    【讨论】:

    • 除非它是公共 API,否则 Access-Control-Allow-Origin 不应该是 *
    猜你喜欢
    • 2020-06-01
    • 2019-10-24
    • 2021-12-01
    • 2020-01-31
    • 2019-05-12
    • 2018-05-31
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多