Laravel API Rest在设备Android中不起作用 [英] Laravel API Rest doesn't work in device Android

查看:211
本文介绍了Laravel API Rest在设备Android中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IONIC中有一个应用程序,并且在浏览器中对API的调用有效,但是当我在android设备上运行时,会显示此错误:

I have an app in IONIC and in browser the call to API works but when I run on android device it shows this error:

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服务-主机192.168.1.***-端口8080

In IONIC I send like API_URL = 'http://192.168.1.***:8080/api/'; to use HttpClient, and in Laravel I run php artisan serve --host 192.168.1.*** --port 8080

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

Please, someone knows what I should do to work?

推荐答案

问题与 CORS .您无需对IONIC应用程序做任何事情.您可以通过添加必需的标头来启用CORS请求,以便您可以在Laravel中创建自己的中间件来处理cors,示例中间件应为:

The issue is related to CORS. You don't have to do anything to your IONIC app. You can enable CORS request by adding required headers for that you can create your own middleware in Laravel to handle cors, A sample middleware would be:

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

Then use it, by editing 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,
]

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

You can customize the above middleware as required.

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

However, if you don't want to do create your own middleware you can use this library: https://github.com/barryvdh/laravel-cors

这篇关于Laravel API Rest在设备Android中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆