Using:
Back: Laravel/Passport Front: ReactJs/Axios
I want to get data in my page, and if I run:
axios.get('http://localhost:8000/api/posts')
.then(response => {
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
GET http://localhost:8000/api/posts net::ERR_ABORTED 401 (Unauthorized)
Access to XMLHttpRequest at 'http://localhost:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And if I add:
headers: {
Authorization: 'Bearer ' + token,
crossDomain: true,
'Access-Control-Allow-Origin': '*'
}
Access to XMLHttpRequest at 'http://localhost:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
In laravel/ api.php:
Route::middleware('auth:api')->group(function () {
Route::get('posts', 'PostController@index');
});
AuthServiceProvider.php
$this->registerPolicies();
Route::group([ 'middleware' => [ \App\Http\Middleware\CORS::class ]], function() {
Passport::routes();
});
RouteServiceProvider.php
$this->mapApiRoutes();
$this->mapWebRoutes();
Route::group([
'middleware' => ['auth:api', 'cors'],
'namespace' => $this->namespace,
'prefix' => 'auth:api',
], function ($router) {
Route::apiResource('posts','PostController');
});
But if I remove headers from axios and also move route outside of passport auth, it work fine, I mean like this outside of group:
Route::get('posts', array('middleware' => 'cors', 'uses' => 'PostController@index'));
So, how can I get data from Laravel API with passport auth with axios in reactjs?
UPDATE:
Route::group(['prefix' => 'auth:api', 'middleware' => 'cors'], function(){
Route::get('posts', 'PostController@index');
});
404 (Not Found)
I used cors on group too, but still the same and 404 error.
corsmiddleware on the group. - Davin TryonRouteServiceProvider.phpand alsoAuthServiceProvider.phpnothing different - tour travelcorsas first one.. - PantherRoute::group([ 'middleware' => ['cors', 'auth:api'],...- Panther