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

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

2 Answers 2

2

I added

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

ok, so you mean that my api is perfectly fine the problem is in ionic config file.?
@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 <allow-navigation> tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.