I have a Laravel API on my localhost (http://localhost:8000) And I have React APP on my localhost (http://localhost:3000)
When I try to post Auth with Axios, I've error that;
"Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. XMLHttpRequest cannot load http://localhost:8000/api/login due to access control checks. http://localhost:8000/api/login Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Unhandled Promise Rejection: Error: Network Error"
I'm sharing you my Laravel Cors codes and my react codes. What could be problem?
When I try to post with "postman" Response Headers show me Access-Control-Allow-Origin is allowed by "*".
Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
'cors'
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'cors' => \App\Http\Middleware\Cors::class // <-- add this line
];
routes/api.php
Route::group(['middleware' => ['cors']], function () {
Route::post('register', 'AuthController@register');
Route::post('login', 'AuthController@login');
Route::post('me', 'AuthController@me');
Middleware/CORS.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
}
}
And my basic React Axios call;
function loginWithEmailSaga(payload) {
const { email, password } = payload;
axios.post(
loginUrl,
{ email, password }
)
.then(res => {
console.log(res);
});
}
I don't see any reason why It gives CORS error. Everything seemed "allowed". What could be the problem? What can I do to handle that thing?