当我需要发送帖子请求以使用api创建Google日历事件时,在laravel 5.8 / jquery 3.4.1应用程序中遇到了CORS政策错误,
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');
}
}
在js代码中,我发送发布请求:
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
我安装了https://github.com/barryvdh/laravel-cors软件包,并保留了文件config / cors.php而不作任何更改:
<?php
return [
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
在routes / web.php中,我添加了HandleCors中间件:
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);
,我希望可以解决我的问题,但是我仍然遇到此错误:https://imgur.com/a/uyTy30Y
如何修复?
答案 0 :(得分:1)
我在这里找到了一个决定:Access-Control-Allow-Origin error sending a jQuery Post to Google API's
通过添加附加参数crossDomain和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
});