简体   繁体   English

Laravel 5.5 ajax 调用 419(未知状态)

[英]Laravel 5.5 ajax call 419 (unknown status)

I do an ajax call but I keep getting this error:我做了一个ajax调用,但我不断收到这个错误:

419 (unknown status) 419(未知状态)

No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this.不知道是什么原因导致我在其他帖子上看到它必须使用 csrf 令牌做一些事情,但我没有表格所以我不知道如何解决这个问题。

my call:我的电话:

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

My route:我的路线:

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

My controller method我的控制器方法

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

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

The ultimate goal is to display something from the response in a html element.最终目标是在 html 元素中显示响应中的某些内容。

Use this in the head section:在 head 部分使用它:

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

and get the csrf token in ajax:并在ajax中获取csrf令牌:

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

Please refer Laravel Documentation csrf_token请参考 Laravel 文档csrf_token

Another way to resolve this is to use the _token field in ajax data and set the value of {{csrf_token()}} in blade.解决此问题的另一种方法是使用 ajax 数据中的_token字段并在刀片中设置{{csrf_token()}}的值。 Here is a working code that I just tried at my end.这是我刚刚尝试过的工作代码。

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

    },
});

This is similar to Kannan's answer.这类似于 Kannan 的回答。 However, this fixes an issue where the token should not be sent to cross-domain sites.但是,这解决了不应将令牌发送到跨域站点的问题。 This will only set the header if it is a local request.如果它是本地请求,这只会设置标头。

HTML: HTML:

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

JS: JS:

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

It's possible your session domain does not match your app URL and/or the host being used to access the application.您的会话域可能与您的应用程序 URL 和/或用于访问应用程序的主机不匹配。

1.) Check your .env file: 1.) 检查您的 .env 文件:

SESSION_DOMAIN=example.com
APP_URL=example.com

2.) Check config/session.php 2.) 检查 config/session.php

Verify values to make sure they are correct.验证值以确保它们正确。

use this in your page在您的页面中使用它

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

and in your ajax used it in data:并在您的 ajax 数据中使用它:

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

that is:即:

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

Thanks.谢谢。

If you already done the above suggestions and still having the issue.如果您已经完成了上述建议,但问题仍然存在。

Make sure that the env variable:确保 env 变量:

SESSION_SECURE_COOKIE

Is set to false if you don't have a SSL certificate, like on local.如果您没有 SSL 证书(例如在本地),设置为false

in my case i forgot to add csrf_token input to the submitted form.就我而言,我忘记将 csrf_token 输入添加到提交的表单中。 so i did this HTML:所以我做了这个 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: 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

If you are loading .js from a file you have to set a variable with the csrf_token in your "main" .blade.php file where you are importing the .js and use the variable in your ajax call.如果您从文件加载 .js,则必须在“主”.blade.php 文件中使用 csrf_token 设置一个变量,您将在其中导入 .js 并在 ajax 调用中使用该变量。

index.blade.php index.blade.php

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

anotherfile.js另一个文件.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
    }
});

Even though you have a csrf_token , if you are authenticate your controller actions using Laravel Policies you can have 419 response as well.即使您有csrf_token ,如果您使用 Laravel Policies对控制器操作进行身份验证,您也可以获得 419 响应。 In that case you should add necessary policy functions in your Policy class.在这种情况下,您应该在Policy类中添加必要的策略函数。

some refs =>一些参考 =>

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

This worked for me:这对我有用:

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

After this set regular AJAX call.此后设置常规 AJAX 调用。 Example:示例:

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

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

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

You have to get the csrf token..你必须得到 csrf 令牌..

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

After doing same issue is rise ,Just Add this meta tag < meta name="csrf-token" content="{{ csrf_token() }}" >做同样的问题后,只需添加这个元标记< meta name="csrf-token" content="{{ csrf_token() }}" >

After this also the error arise ,you can check the Ajax error.在此之后也出现错误,您可以检查 Ajax 错误。 Then Also check the Ajax error然后还要检查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);
    },
});
formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);

2019 Laravel Update, Never thought i will post this but for those developers like me using the browser fetch api on Laravel 5.8 and above. 2019 Laravel 更新,没想到我会发布这个,但对于像我这样在 Laravel 5.8 及更高版本上使用浏览器获取 api 的开发人员。 You have to pass your token via the headers parameter.您必须通过 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));

如果您忘记在您的 ajax 提交请求 ( POST ), contentType: false, processData: false, 中包含此错误,也会发生此错误

This works great for those cases you don't require a form.这对于不需要表单的情况非常有用。

use this in header:在标题中使用它:

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

and this in your JavaScript code:这在您的 JavaScript 代码中:

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

Got this error even though I had already been sending csrf token.即使我已经发送了 csrf 令牌,也收到此错误。 Turned out there was no more space left on server.原来服务器上没有更多空间了。

A simple way to fixe a 419 unknown status on your console is to put this script inside in your FORM.在您的控制台上修复 419 未知状态的一种简单方法是将此脚本放入您的 FORM 中。 {{ csrf_field() }} {{ csrf_field() }}

in the name of the universe programmer以宇宙程序员的名义

i send ajax with pure js and i understand when i dont set this method of ajax in pure js << xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") >> i recive this error 419.我用纯 js 发送 ajax,我明白当我没有在纯 js 中设置这种 ajax 方法 << xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") >> 我收到这个错误419.

the full method of pure ajax is :纯ajax的完整方法是:

let token = document.querySelector('meta[name="csrf-token"]').content;让 token = document.querySelector('meta[name="csrf-token"]').content;

let xhr = new XMLHttpRequest();让 xhr = new XMLHttpRequest();

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

// you have to set this line in the code (if you dont set you recive error 419): // 你必须在代码中设置这一行(如果你没有设置你会收到错误 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}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM