簡體   English   中英

Laravel Ajax請求,沒有“ Access-Control-Allow-Origin”標頭

[英]Laravel Ajax request, No 'Access-Control-Allow-Origin' header

今天,我使用Heroku擴展了我的工作流程,當我啟動並運行了所有內容並開始測試諸如注冊/登錄模態之類的東西時,我將這個錯誤發送到控制台。

從CORS策略阻止從原點“ https://app-name.herokuapp.com ”訪問“ http://app-name.herokuapp.com/register ”處的XMLHttpRequest:對預檢請求的響應未通過訪問控件檢查:所請求的資源上不存在“ Access-Control-Allow-Origin”標頭。

嘗試將Content-Security-Policy添加到布局文件的標頭中,也將X-CSRF-TOKEN添加到我的Ajax請求標頭中,從而刪除了部分錯誤,但隨后僅搜索了不同的解決方案並對其進行了嘗試。

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
 $(document).on('submit', '#formRegister', function(e) {
            e.preventDefault();

            $('input+small').text('');
            $('#formRegister input').removeClass('is-invalid');

            $.ajax({
                method: $(this).attr('method'),
                url: $(this).attr('action'),
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Access-Control-Allow-Methods' : 'POST',
                    'Access-Control-Allow-Headers' : 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization'
                },
                data: $(this).serialize(),
                dataType: "json",
                crossDomain: false
            })
                .done(function(data) {
                    $('.success-registered').removeClass('d-none');
                    $('#formRegister input').val('');
                    setTimeout(function() {
                        $('.success-registered').addClass('d-none');
                        location.reload();
                    }, 3000);
                    $('#login').modal('hide');
                })
                .fail(function(data) {
                    if (data.status === 422 && data.responseJSON) {
                        if (Object.keys(data.responseJSON.errors).length) {
                            for (field in data.responseJSON.errors) {
                                var error = data.responseJSON.errors[field];
                                var input = '#formRegister input[name=' + field + ']';
                                $(input).addClass('is-invalid');
                                $(input).next('span').find('strong').text(error[0]);
                            }
                        }
                    }
                });
        });
public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: response()->json();
    }
 protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: response()->json();
    }

除了用於驗證的JSON輸出外,我還根據控制器的成功請求重新加載頁面。

您的站點具有不同的協議。 一個使用http ,另一個使用https 根據MDN

Web應用程序請求其來源(域, 協議和端口)與其自身來源不同的資源時,將執行跨域HTTP請求。

跨域資源共享

要解決此問題,請對兩個站點使用相同的協議。

在標題中:

<meta name="csrf-token" content="{{ csrf_token() }}" />

在表單中添加csrf字段

<form action="your action" method="post">
  @csrf

  <!-- your other fields -->
</form>

在js代碼中:

$(document).on('submit', '#formRegister', function(e) {
            e.preventDefault();

            $('input+small').text('');
            $('#formRegister input').removeClass('is-invalid');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                method: $(this).attr('method'),
                url: $(this).attr('action'),                
                data: $(this).serialize(),
                dataType: "json",
                cache: false,
                crossDomain: false
            })
                .done(function(data) {
                    $('.success-registered').removeClass('d-none');
                    $('#formRegister input').val('');
                    setTimeout(function() {
                        $('.success-registered').addClass('d-none');
                        location.reload();
                    }, 3000);
                    $('#login').modal('hide');
                })
                .fail(function(data) {
                    if (data.status === 422 && data.responseJSON) {
                        if (Object.keys(data.responseJSON.errors).length) {
                            for (field in data.responseJSON.errors) {
                                var error = data.responseJSON.errors[field];
                                var input = '#formRegister input[name=' + field + ']';
                                $(input).addClass('is-invalid');
                                $(input).next('span').find('strong').text(error[0]);
                            }
                        }
                    }
                });
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM