0

i create a api which return the list of users.i test it in postman app and working fine (return json) . but when i try to call it in ionic2 then it show me error in console.i try to insert header('Access-Control-Allow-Origin: *'); in public/index.php at the top . and also try to make a middleware and the handler() has following code

return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

route/api.php

Route::group(['middleware' => ['Cors']] ,function(){

     Route::get('/nearby',['as' => 'people.nearby' , 'uses' => function(){
       return User::all();
     }]);
});

and inside kernel.php($routeMiddleware) i add alliance as 'Cors' => \App\Http\Middleware\Cors::class

i try to call a test api link(https://randomuser.me/api/) from the google to check if my js or typescript code is working fine and i got the response with json but got error of Allow Access Origin while calling my laravel api . where i am going wrong or some error in my code . any help will appreciated.

Here is the request result of api from network tab(Developer mode). network request result

sandeep
  • 501
  • 4
  • 16
  • can you post the error in console message? – Icycool Sep 07 '17 at 04:50
  • and also the request/response header as example https://stackoverflow.com/a/40359870/5039495 – Icycool Sep 07 '17 at 04:53
  • XMLHttpRequest cannot load http://localhost/social/public/api/nearby. The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access. – sandeep Sep 07 '17 at 11:26
  • @Icycool .i insert the network request response image, please take a look once thanku – sandeep Sep 07 '17 at 11:37
  • It is complaining you having 2 lines of `Access-Control-Allow-Origin` – Icycool Sep 07 '17 at 18:08

2 Answers2

2

I added

header('Access-Control-Allow-Origin: *');

in public/index.php and removed the Cors middleware and all done.

Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
sandeep
  • 501
  • 4
  • 16
1

Probably because Ionic2 itself has not been allowed to make network requests to your endpoint.

You will need to update the Ionic2 app not the server-side (Laravel).

In your Ionic2 config.xml you most likely need to adjust the access attribute, see the documentation here:

https://cordova.apache.org/docs/en/latest/config_ref/#access

Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • ok, so you mean that my api is perfectly fine the problem is in ionic config file.? – sandeep Sep 06 '17 at 17:37
  • @sandeep indeed, if you've enabled CORS on server-side, the issue could be from your Ionic app. `config.xml` should be on root folder, and you'll have to edit `` tag – Zooly Sep 06 '17 at 19:11