-1

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?

sadjapa
  • 15
  • 10
  • code error 0 is a CORS FAILURE , maybe this can help : https://stackoverflow.com/questions/47180634/i-get-http-failure-response-for-unknown-url-0-unknown-error-instead-of-actu – Sam Nov 18 '19 at 14:14
  • I configured config.xml and network_security_config.xml to allow everthing but doesn't work – sadjapa Nov 18 '19 at 14:41

1 Answers1

1

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

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.

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

  • I edited Cors and Kernel, used API_URL = 'http: //192.168.1.***: 8000 / api / again but doesn't work – sadjapa Nov 19 '19 at 12:37
  • I need to edit something in .env? `APP_NAME=Laravel APP_ENV= local APP_KEY=base64:IokQpQNAF277VRJSWIUSxJ8iUSOjX5Rv/6U8Cd6HLuo= APP_DEBUG=true APP_URL=http://localhost` – sadjapa Nov 19 '19 at 12:52