Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
164 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 AppHttpMiddleware;

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', '*');    
    }
}

Then use it, by editing appHttpKernel.php

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

]
protected $routeMiddleware = [
    // other middleware code
   'cors' => EuroKidsHttpMiddlewareCors::class,
]

You can customize the above middleware as required.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...