0
votes

I'm trying to pull data from a weather API on my localhost environment and I'm getting a 405 Error(Method not allowed) as well as "has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status." I've config'd my headers and can't figure out what i'm doing wrong. It works fine on live but obviously that's not a convenient way doing it.

I've tried using axios.get as well as axios.post.

var config = {
    headers: {'Access-Control-Allow-Origin': '*'}
};
getWeather: function (){
    axios.get('http://api.openweathermap.org/data/2.5/forecast?id='+ city + '&appid='+ apiKey, config).then((res) => {this.weather = res.data});
}
1
can you show the error message? - Imanali Mamadiev
I think chrome blocks it by default. Try other browser maybe? - Pradeepb

1 Answers

0
votes

Hope adding below package will help

use this https://github.com/barryvdh/laravel-cors

Installation :

composer require barryvdh/laravel-cors

Service provider :

Add this Barryvdh\Cors\ServiceProvider::class, in config/app.php

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

protected $middleware = [
 \Barryvdh\Cors\HandleCors::class,
 // ...
];

NOTE: make sure to place it before all middlewares

If it's for specific middleware, on our case, it will be api

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

'api' => [
    \Barryvdh\Cors\HandleCors::class, 
    'throttle:60,1',
    'bindings',
],

];

NOTE: make sure to place it before all middlewares

Publish the config :

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