it-source

Larabel 5.5 ajax 콜 419(알 수 없는 상태)

criticalcode 2022. 12. 29. 20:30
반응형

Larabel 5.5 ajax 콜 419(알 수 없는 상태)

Ajax 콜을 실행했는데 다음 오류가 계속 나타납니다.

419(스테이터스)

다른 투고에서도 원인을 알 수 없습니다만, CSRF 토큰과 관계가 있습니다만, 폼이 없기 때문에 어떻게 수정해야 할지 모르겠습니다.

내 전화:

$('.company-selector li > a').click(function(e) {
     e.preventDefault();

     var companyId = $(this).data("company-id");


      $.ajax({
          headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {},
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });
  });

내 경로:

Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');

마이 컨트롤러 방식

/**
 * Fetches a company
 *
 * @param $companyId
 *
 * @return array
 */
public function fetchCompany($companyId)
{
    $company = Company::where('id', $companyId)->first();

    return response()->json($company);
}

최종적인 목표는 응답의 내용을 html 요소로 표시하는 것입니다.

머리 부분에 이것을 사용합니다.

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

ajax에서 csrf 토큰을 가져옵니다.

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

Laravel Documentation csrf_token을 참조하십시오.

문제를 하는 또 다른 으로는 이 문제를 ._token하고 Ajax 합니다.{{csrf_token()}}here here here here that that a is is a 。여기 제가 방금 시도한 작업 코드가 있습니다.

$.ajax({
    type: "POST",
    url: '/your_url',
    data: { somefield: "Some field value", _token: '{{csrf_token()}}' },
    success: function (data) {
       console.log(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);

    },
});

세션 도메인이 앱 URL 및/또는 애플리케이션에 액세스하는 데 사용되는 호스트와 일치하지 않을 수 있습니다.

1) .env 파일을 확인합니다.

SESSION_DOMAIN=example.com
APP_URL=example.com

2) 설정/세션을 확인합니다.php

값이 올바른지 확인합니다.

이것은 Kannan의 대답과 유사하다.단, 토큰이 교차 도메인 사이트로 전송되지 않아야 하는 문제가 해결되었습니다.로컬 요청일 경우에만 헤더가 설정됩니다.

HTML:

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

JS:

$.ajaxSetup({
    beforeSend: function(xhr, type) {
        if (!type.crossDomain) {
            xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
        }
    },
});

이것을 당신의 페이지에 사용하세요.

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

그리고 당신의 에이잭스에서는 그것을 데이터에 사용했습니다.

_token: '{!! csrf_token() !!}',

즉, 다음과 같습니다.

$.ajax({
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {
                   _token: '{!! csrf_token() !!}',
                 },
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });

감사해요.

이미 위의 제안을 했는데도 문제가 있는 경우.

env 변수가 다음 중 하나인지 확인합니다.

SESSION_SECURE_COOKIE

로 설정되어 있다.false 로컬과 같이 SSL 인증서가 없는 경우

제 경우 csrf_token 입력을 제출 양식에 추가하는 것을 잊었습니다.그래서 다음 HTML을 실행했습니다.

<form class="form-material" id="myform">
...
<input type="file" name="l_img" id="l_img">
<input type="hidden" id="_token" value="{{ csrf_token() }}">
..
</form>

JS:

//setting containers
        var _token = $('input#_token').val();
        var l_img = $('input#l_img').val();
        var formData = new FormData();
        formData.append("_token", _token);
        formData.append("l_img", $('#l_img')[0].files[0]);

        if(!l_img) {
            //do error if no image uploaded
            return false;
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "/my_url",
                contentType: false,
                processData: false,
                dataType: "json",
                data : formData,
                beforeSend: function()
                {
                    //do before send
                },
                success: function(data)
                {
                    //do success
                },
                error: function(jqXhr, textStatus, errorThrown) //jqXHR, textStatus, errorThrown
                {
                    if( jqXhr.status === "422" ) {
                        //do error
                    } else {
                        //do error
                    }
                }
            });
        }
        return false; //not to post the form physically

파일에서 .js를 로드하는 경우 "main" .blade에서 csrf_token을 사용하여 변수를 설정해야 합니다.php 파일에는 .diags를 Import하여 ajax 호출에 변수를 사용합니다.

index.blade.php

...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
        var token = '{{ csrf_token() }}';
</script>

another file.displays 를 지정합니다.

$.ajax({
    url: 'yourUrl',
    type: 'POST',
    data: {
        '_token': token
    },
    dataType: "json",
    beforeSend:function(){
        //do stuff
    },
    success: function(data) {
        //do stuff
    },
    error: function(data) {
        //do stuff
    },
    complete: function(){
        //do stuff
    }
});

csrf_tokenLaravel Larabel을 하여 Policies 수 요.419번 응답하다.가 있습니다.Policy를 누릅니다

일부 참조 =>

...
<head>
    // CSRF for all ajax call
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
 ...
 ...
<script>
    // CSRF for all ajax call
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });
</script>
...

CSRF 토큰을 가져와야 합니다.

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

가 상승하면 이 해 버립니다.< meta name="csrf-token" content="{{ csrf_token() }}" >

이 오류도 발생한 후 Ajax 오류를 확인할 수 있습니다.그런 다음 Ajax 오류도 확인합니다.

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

2019년 Laravel Update, 나 같은 개발자가 Laravel 5.8 이상에서 브라우저 fetch api를 사용하는 것 이외에는 이 글을 올릴 줄 몰랐다.헤더 파라미터를 통해 토큰을 전달해야 합니다.

var _token = "{{ csrf_token }}";
fetch("{{url('add/new/comment')}}", {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': _token,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(name, email, message, article_id)
            }).then(r => {
                return r.json();
            }).then(results => {}).catch(err => console.log(err));

이 방법은 효과가 있었습니다.

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
  }
});

이 후에, 통상의 AJAX 콜을 설정합니다.예:

    $.ajax({
       type:'POST',
       url:'custom_url',

       data:{name: "some name", password: "pass", email: "test@test.com"},

       success:function(response){

          // Log response
          console.log(response);

       }

    });

나는 가지고 있었다SESSION_SECURE_COOKIE로그인 시 개발 환경이 작동하지 않도록 true로 설정했습니다.SESSION_SECURE_COOKIE=false제 dev .env 파일에 모든 것이 정상적으로 동작하고 있습니다.실수는 변수를 .env 파일에 추가하는 대신 session.env 파일을 변경하는 것이었습니다.

폼 데이터를 시리얼화하여 문제를 해결합니다.

data: $('#form_id').serialize(),
formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);

이 에러는, 이것을 Ajax 송신 요구(POST)에 포함시키는 것을 잊은 경우에도 발생합니다.유형: false, processData: false,

이미 CSRF 토큰을 송신하고 있었는데도, 이 에러가 발생했습니다.서버에 더 이상 공간이 남아 있지 않은 것으로 나타났습니다.

이 방법은 양식이 필요 없는 경우에 적합합니다.

헤더에서 사용:

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

JavaScript 코드로 다음과 같이 입력합니다.

$.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
        }
    });

콘솔에서 알 수 없는 419 상태를 수정하는 간단한 방법은 이 스크립트를 폼 안에 넣는 것입니다.{{csrf_field()}}

우주 프로그래머의 이름으로

순수 js를 사용하여 ajax를 전송하고, 순수 js < xhr.setRequest에 이 ajax 메서드를 설정하지 않은 경우를 이해한다.Header("Content-type", "application/x-www-form-urlencoded") >> 이 에러 419 를 수신합니다.

순수 아약스의 전체 방법은 다음과 같습니다.

토큰 =을(를) 문서화합니다.querySelector('meta[name="csrf-token")).내용;

xhr = new XMLHttpRequest()로 합니다.

// Open the connection
xhr.open("POST", "/seller/dashboard/get-restaurants");

// 코드에서 다음 행을 설정해야 합니다(설정하지 않으면 오류 419가 발생합니다).

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//* Set up a handler for when the task for the request is complete
xhr.onload = function () {
    
};

// Send the data.
xhr.send(`_token=${token}`);

언급URL : https://stackoverflow.com/questions/46466167/laravel-5-5-ajax-call-419-unknown-status

반응형