【问题标题】:Laravel API Rest doesn't work in device AndroidLaravel API Rest 在设备 Android 中不起作用
【发布时间】:2020-03-13 21:44:51
【问题描述】:

我在 IONIC 中有一个应用,在浏览器中可以调用 API,但是当我在 android 设备上运行时,它会显示此错误:

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://192.168.1.***:8080/api/auth/login", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://192.168.1.***:8080/api/auth/login: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://192.168.1.***:8080/api/auth/login"
__proto__: HttpResponseBase

在 IONIC 中我发送 API_URL = 'http://192.168.1.***:8080/api/'; 以使用 HttpClient,在 Laravel 中我运行 php artisan serve --host 192.168.1.*** --port 8080

请问,有人知道我应该做什么工作吗?

【问题讨论】:

标签: android laravel api ionic-framework httpclient


【解决方案1】:

该问题与CORS 有关。您无需对您的 IONIC 应用程序执行任何操作。您可以通过添加所需的标头来启用 CORS 请求,您可以在 Laravel 中创建自己的中间件来处理 cors,示例中间件是:

namespace App\Http\Middleware;

use Closure;

class Cors
{    
    public function handle($request, Closure $next)
    {
        return $next($request)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', '*');    
    }
}

然后使用它,通过编辑 app\Http\Kernel.php

 protected $middlewareGroups = [
    'web' => [
     // middleware for your web routes
    ],
    'api' => [
        'throttle:60,1',
        'bindings',
        'cors',
    ],

]
protected $routeMiddleware = [
    // other middleware code
   'cors' => \EuroKids\Http\Middleware\Cors::class,
]

您可以根据需要自定义上述中间件。

但是,如果您不想创建自己的中间件,您可以使用这个库: https://github.com/barryvdh/laravel-cors

【讨论】:

  • 我编辑了 Cors 和 Kernel,再次使用了 API_URL = 'http://192.168.1.***: 8000 / api/ 但不起作用
  • 我需要在 .env 中编辑一些东西吗? APP_NAME=Laravel APP_ENV= local APP_KEY=base64:IokQpQNAF277VRJSWIUSxJ8iUSOjX5Rv/6U8Cd6HLuo= APP_DEBUG=true APP_URL=http://localhost
猜你喜欢
  • 2022-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多