Laravel API Rest在设备Android中不起作用

我在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

请,有人知道我该怎么做?

huhanz 回答:Laravel API Rest在设备Android中不起作用

问题与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

本文链接:https://www.f2er.com/3080581.html

大家都在问