Laravel 5.5 ajax 拨打 419(未知状态)

Laravel 5.5 ajax call 419 (unknown status)

我打了一个 ajax 电话,但我一直收到这个错误:

419 (unknown status)

不知道是什么原因造成的,我在其他帖子上看到它必须用 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文档csrf_token

这与Kannan 的回答类似。但是,这解决了不应将令牌发送到 cross-domain 个站点的问题。如果是本地请求,这只会设置 header。

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'));
        }
    },
});

在我的例子中,我忘记在提交的表单中添加 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

即使您有 csrf_token,如果您使用 Laravel Policies 验证您的控制器操作,您也可以获得 419 响应。在这种情况下,您应该在 Policy class.

中添加必要的政策功能

解决此问题的另一种方法是使用 ajax 数据中的 _token 字段并在 blade 中设置 {{csrf_token()}} 的值。这是我刚试过的有效代码。

$.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);

    },
});

如果您已经完成了上述建议,但问题仍然存在。

确保环境变量:

SESSION_SECURE_COOKIE

设置为false 如果你没有SSL证书,就像在本地一样。

在您的页面中使用它

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

并在您的 ajax 数据中使用了它:

_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);
          }
     });

谢谢。

您的会话域可能与您的应用程序不匹配 URL and/or 用于访问应用程序的主机。

1.) 检查您的 .env 文件:

SESSION_DOMAIN=example.com
APP_URL=example.com

2.) 检查config/session.php

验证值以确保它们正确。

一些参考 =>

...
<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>
...

如果要从文件加载 .js,则必须在要导入 .js 的 "main".blade.php 文件中使用 csrf_token 设置一个变量并使用ajax 调用中的变量。

index.blade.php

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

anotherfile.js

$.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
    }
});

只需序列化表单数据即可解决您的问题。

data: $('#form_id').serialize(),

您必须获得 csrf 令牌..

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

做完同样的问题后,添加这个meta标签就可以了< 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);
    },
});

如果您忘记在 ajax 提交请求 ( POST ) 中包含此内容,也会发生此错误, 内容类型:假, 处理数据:假,

这对于不需要表格的情况非常有用。

在header中使用这个:

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

在您的 JavaScript 代码中:

$.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
        }
    });
formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);

尽管我已经发送了 csrf 令牌,但还是出现了这个错误。原来服务器上已经没有 space 了。

修复控制台上的 419 未知状态的一种简单方法是将此脚本放入 FORM 中。 {{ csrf_field() }}

2019 Laravel 更新,从没想过我会 post 这个但是对于像我这样使用浏览器获取 api Laravel 5.8 及更高版本的开发者。您必须通过 headers 参数传递您的令牌。

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 到我的开发 .env 文件并且一切正常我的错误是更改 session.php 文件而不是将变量添加到 .env 文件。