mstdmstd
2 months ago

In ajax post request my app blocked by CORS policy error

Posted 2 months ago by mstdmstd

I encountered CORS policy error in my laravel 5.8 / jquery 3.4.1 app when I need send post request to create google calendar event with api like:

    public function calendar_add_event(Request $request)
    {
        session_start();
        $startDateTime = $request->start_date;
        $endDateTime = $request->end_date;

        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            $this->client->setAccessToken($_SESSION['access_token']);
            $service = new Google_Service_Calendar($this->client);

            $calendarId = 'primary';
            $event = new Google_Service_Calendar_Event([
                'summary' => $request->title,
                'description' => $request->description,
                'start' => ['dateTime' => $startDateTime],
                'end' => ['dateTime' => $endDateTime],
                'reminders' => ['useDefault' => true],
            ]);
            $results = $service->events->insert($calendarId, $event);
            if (!$results) {
                return response()->json(['status' => 'error', 'message' => 'Something went wrong']);
            }
            return response()->json(['status' => 'success', 'message' => 'Event Created']);
        } else {
            return redirect()->route('oauthCallback');
        }
    }

In js code I send post request :

backendCalendar.prototype.saveCalendarAddEvent = function (user_id) {
    var href = this_backend_home_url + "/admin/calendar_add_event";
    $.ajax( {
        type: "POST",
        dataType: "json",
        url: href,
        data: { "title": $('#new_event_title').val(),   "description": $('#new_event_description').val(),   "start_date": $('#new_event_start_date').val(),   "end_date": $('#new_event_end_date').val(),     "_token": this_csrf_token},
        success: function( response )
        {
            popupAlert("New event was added successfully !", 'success')
        },
        error: function( error )
        {
            popupErrorMessage(error.responseJSON.message)
        }
    });

} // backendCalendar.prototype.saveCalendarAddEvent

I installed https://github.com/barryvdh/laravel-cors package and left file config/cors.php without changes :

<?php

return [   
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,

];

in routes/web.php I added HandleCors middleware :

Route::group(['middleware' => ['auth', 'isVerified', 'CheckUserStatus'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
   ...
    Route::post('calendar_add_event', '[email protected]_add_event')->middleware(\Barryvdh\Cors\HandleCors::class);

and I hoped that would fix my problems, but I still have this error : https://imgur.com/a/uyTy30Y

How to fix it ?

Please sign in or create an account to participate in this conversation.