0

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', 'gCalendarController@calendar_add_event')->middleware(\Barryvdh\Cors\HandleCors::class);

and I hoped that would fix my problems, but I still have this error : https://i.stack.imgur.com/PXBdN.jpg

How to fix it ?

mare96
  • 3,749
  • 1
  • 16
  • 28
mstdmstd
  • 2,195
  • 17
  • 63
  • 140

1 Answers1

1

I found a decision here : Access-Control-Allow-Origin error sending a jQuery Post to Google API's

by additing additive parameters crossDomain and modification of dataType :

$.ajax({

    url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
    data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});
mstdmstd
  • 2,195
  • 17
  • 63
  • 140