Laravel v8.61.0 (PHP v8.0.9) cors Issue API POST

  axios, cors, laravel, laravel-8, reactjs

I am new to laravel, I am having an issue with cors. I followed a few tutorials, and try various methods to get cors working, but I am not having any luck and am not sure what i am doing wrong.

Bellow is the code I am using.

I want to get simple response from server after posting to server, I just want to have a basic response so I know it is working on post

I am using react with axios

<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*') //add this
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');  //add this
    }
}
<?php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // AppHttpMiddlewareTrustHosts::class,
        AppHttpMiddlewareTrustProxies::class,
        FruitcakeCorsHandleCors::class,
        AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
        AppHttpMiddlewareCors::class,  // add this
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],

        'api' => [
            // LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            IlluminateRoutingMiddlewareSubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => AppHttpMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
        'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
        'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
        'cors' => AppHttpMiddlewareCors::class,   //add this
    ];
}

api.php

<?php

use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});


Route::get('/user', function () {
    return["test"=> "get"];
});


Route::middleware("cors")->post('/login', function () {
    return["test"=> "test"];  // Trying to get this one to work
});

Front end code

        axios.post('localhost:8000/api/login', {
            userId: '0',
            password: '0'
          })
          .then(function (response) {
            console.log(response);
            props.authenticate(true);
            history.push('/');
          })
          .catch(function (error) {
            console.log(error);
          });

Source: Laravel

Leave a Reply