使用 Laravel 作为 REST API 在移动设备上使用 Ionic 4 应用程序的本地 CORS 问题

Posted

技术标签:

【中文标题】使用 Laravel 作为 REST API 在移动设备上使用 Ionic 4 应用程序的本地 CORS 问题【英文标题】:Local CORS Issues with Ionic 4 Application on mobile Device using Laravel as REST API 【发布时间】:2019-10-25 22:42:57 【问题描述】:

我已经尝试过在万维网上发布的任何类型的解决方案。

    重现简单,创建一个全新的 Laravel 应用程序并配置 API 路由以接收 get/post 请求。

    创建 Ionic 应用程序并向 API 发送 get/post 请求。

    在浏览器上试一试,根据需要设置CORS,之后浏览器就可以工作了。

    在移动设备(iosandroid)上尝试,即使配置了CORS,也无法正常工作。

    我已经构建了一个带有 api get/post 路由的全新 Laravel 应用程序,以及一个使用 Angular HttpClient 的全新 ionic 应用程序,还尝试使用 Cordova 的 NativeHttp 插件。现在,一个简单的 get Request 在浏览器(离子服务)中没有问题。如果我尝试在移动设备上发送 get/post 请求,我会收到“消息”:“http://127.0.0.1:8000/api/login 的 Http 失败响应:0 未知错误”以及 Angular 和本机调用的 HTTPClient 错误:“status”:- 1,"error":"Could not connect to the server." 使用 NativeHTTP 插件。

我尝试在 Laravel API 中设置 CORS,我使用了 barryvdh/laravel-cors,我尝试制作自己的 CORS 中间件,我还尝试了另一个 laravel Cors Package。 Laravel 方面没有任何帮助。

然后我尝试了几个代码和离子应用程序来解决这个问题。包含在标头中,没有简单的请求,NativeHTTP cordova-plugin-advanced-http,Angular HTTP...没有任何效果...

Ionic Doc 中的这个示例不起作用...

    import  HTTP  from '@ionic-native/http/ngx';

    constructor(private http: HTTP) 

    ...

    this.http.get('http://ionic.io', , )
      .then(data => 

        console.log(data.status);
        console.log(data.data); // data received by server
        console.log(data.headers);

      )
      .catch(error => 

        console.log(error.status);
        console.log(error.error); // error message as string
        console.log(error.headers);

      );

我收到“消息”:“(未知 url)的 Http 失败响应:-1 未定义”,在带有 Angular 的 HTTPClient 的浏览器中运行良好。

这也适用于浏览器:

    login(email: String, password: String) 

        return this.http.post('https://127.0.0.1:8000/api/login',
          email: email, password: password
        ).pipe(
          tap(api_token => 
            this.storage.setItem('api_token', api_token)
            .then(
              () => 
                console.log('Token Stored');
              ,
              error => console.error('Error storing item', error)
            );
            this.api_token = api_token;
            this.isLoggedIn = true;
            return api_token;
          ),
        );
      

在 IOS 和 Android 上,我得到:

"message": "http://127.0.0.1:8000/api/login 的 Http 失败响应:0 未知错误"

我尝试在有和没有电容器的情况下使用 Ionic,我尝试使用 ionic run --devapp 以及 ionic cordova run ios,使用 XCODE 等等。

我使用 Ionic 移动应用程序执行的任何 Laravel API 之间的通信都无法使用 Httprequests...

我按照barryvdh包的Cors安装步骤,cors.php是这样的:

    'supportsCredentials' => false,
        'allowedOrigins' => ['*'],
        'allowedOriginsPatterns' => [],
        'allowedHeaders' => ['*'],
        'allowedMethods' => ['*'],
        'exposedHeaders' => [],
        'maxAge' => 0,

还做了 $middleware 步骤以使其全局化并使用终端命令 php artisan vendor:publish -- provider="Barryvdh\Cors\ServiceProvider"。

浏览器在没有配置 CORS 的情况下无法工作,但是当我安装包时,浏览器运行良好。原生应用程序没有任何变化,安装 CORS 打包后它们仍然无法工作......

全部错误:

    "headers": 
    [ng]     "normalizedNames": ,
    [ng]     "lazyUpdate": null,
    [ng]     "headers": 
    [ng]   ,
    [ng]   "status": 0,
    [ng]   "statusText": "Unknown Error",
    [ng]   "url": "http://127.0.0.1:8000/api/login",
    [ng]   "ok": false,
    [ng]   "name": "HttpErrorResponse",
    [ng]   "message": "Http failure response for         http://127.0.0.1:8000/api/login: 0 Unknown Error",
    [ng]   "error": 
    [ng]     "isTrusted": true
    [ng]   
    [ng] 


    [console.log]: "Ionic Native: deviceready event fired after 374 ms"
    [ng] [console.log]: 
    [ng]   "headers": 
    [ng]     "normalizedNames": ,
    [ng]     "lazyUpdate": null,
    [ng]     "headers": 
    [ng]   ,
    [ng]   "status": -1,
    [ng]   "statusText": "Unknown Error",
    [ng]   "url": null,
    [ng]   "ok": false,
    [ng]   "name": "HttpErrorResponse",
    [ng]   "message": "Http failure response for (unknown url): -1         undefined",
    [ng]   "error": "Verbindung zum Server konnte nicht hergestellt werden."
    [ng] 

我知道我已经发布了很多信息,但可能还不够。希望你能理解我的问题,也许有人对 Laravel API 和 Ionic 移动 APP 也有这个问题。

【问题讨论】:

在这里查看***.com/questions/56289595/ionic-cant-get-open-cors/…。 Ionic can't get open cors的可能重复 【参考方案1】:

解决了问题...

我没有托管 API,只是使用 php artisan serve 和 localhost:8000 地址运行它。

我的移动设备无法连接到本地 mac 地址,否则 mac 上的模拟器能够连接到该地址。

因此移动设备响应:“message”:“Http failure response for (unknown url): -1 .

不知道未知的Error 0是怎么发生的,我现在用主机地址试一试。

还是谢谢你。

【讨论】:

嗨。您有解决方案或任何消息吗?我也有同样的问题。此外,当我尝试向远程服务器发送请求时,我收到此错误。

以上是关于使用 Laravel 作为 REST API 在移动设备上使用 Ionic 4 应用程序的本地 CORS 问题的主要内容,如果未能解决你的问题,请参考以下文章

Botman laravel REST API 设置

php 使用Passport进行Laravel REST API身份验证:https://www.cloudways.com/blog/rest-api-laravel-passport-authen

Laravel 5 REST API

Laravel 7 - 使用 REST API 而不是数据库

Laravel REST API - 无限循环

使用 curl - JSON 访问 Laravel Rest API