在 ajax 发布请求中,我的应用被 CORS 策略错误阻止

Posted

技术标签:

【中文标题】在 ajax 发布请求中,我的应用被 CORS 策略错误阻止【英文标题】:In ajax post request my app blocked by CORS policy error 【发布时间】: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

如何解决?

【问题讨论】:

【参考方案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
);

【讨论】:

以上是关于在 ajax 发布请求中,我的应用被 CORS 策略错误阻止的主要内容,如果未能解决你的问题,请参考以下文章

AJAX CORS 请求来源被阻止 - Java Web 服务

Rails 跨域 ajax 获取请求 (CORS)

ajax 发布请求 - 跨域读取阻塞 (CORB) 阻止跨域响应 CORS

错误:laravel/VueJS ajax 请求中的 CORS

CORS - 没有 JSONP 的跨域 AJAX 通过允许服务器上的 Origin

cors / ajax 请求的重复 OPTIONS 请求