【问题标题】:In ajax post request my app blocked by CORS policy error在 ajax 发布请求中,我的应用被 CORS 策略错误阻止
【发布时间】:2019-12-16 20:42:20
【问题描述】:

我在我的 laravel 5.8 / jquery 3.4.1 应用程序中遇到了 CORS 策略错误,当我需要发送发布请求以使用以下 API 创建谷歌日历事件时:

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 代码中我发送 post 请求:

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

如何解决?

【问题讨论】:

    标签: ajax laravel laravel-5 cors


    【解决方案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
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-14
      • 2019-09-30
      • 1970-01-01
      • 2020-06-02
      • 2019-11-30
      • 2019-10-01
      • 2020-08-15
      • 2020-06-13
      • 2021-09-18
      相关资源
      最近更新 更多