2

I've literally just created a new project and made a single route:

Route::get('/getSummoner', 'RiotController@getSummoner');

That executes this function:

public function getSummoner(){

$get = file_get_contents("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/RiotSchmick?api_key=");
$result = json_decode($get);

return response()->json([
    'result' => $result,
], 201);

}

and on the front-end, I get the following error:

Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I understand this happens when the I make a request to a different domain than what my page is on but since the API is not mine, I can't really make a request from the same domain, can I?

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • 3
    [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Jorge Luis Bravo May 30 '19 at 14:30

2 Answers2

0

That message indicates that their API is not allowing your site to access it. It may be allowing you to access it via Postman, direct site visit via URL, or some other direct method...but you need the Access-Control-Allow-Origin header to specifically allow your web domain (which in this case seems to be internal to you) in order to be able to access it.

Luke G.
  • 587
  • 1
  • 4
  • 13
0

CORS is disabled by default in any sites for security purposes. You need to install barryvdh/laravel-cors to allow CORS.

composer require barryvdh/laravel-cors

once installed you need to run this in terminal/command prompt

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

then add the HandleCors in your middleware groups, in your case add it in api middleware

    protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];