php 当我在路由上有 post 方法时,Symfony\Component\HttpKernel\Exception\HttpException 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46186658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:11:52  来源:igfitidea点击:

Symfony\Component\HttpKernel\Exception\HttpException error when I have post method on route

phpjqueryajaxlaravel

提问by Joan Plepi

I am doing an ajax request with jquery and I want to send one data to the server (the id of the clicked button) so I can make the correct query and return the correct reponse. The idea is that after I click a button I should make the ajax call to request a datatable. My jquery function looks like this:

我正在使用 jquery 执行 ajax 请求,我想向服务器发送一个数据(单击按钮的 id),以便我可以进行正确的查询并返回正确的响应。这个想法是,在我单击一个按钮后,我应该进行 ajax 调用以请求数据表。我的 jquery 函数如下所示:

$('button').click(function(){

                var dep_id =  $(this).attr('id');

                var table = $('#dataTable').DataTable( {

                "processing": true,
                "serverSide": true,
                "ajax": {
                            "url" : '{!! route('workerDepData') !!}'  , 
                            "type" : "POST" ,
                            "data" : { id: dep_id } 
                        },
                 columns: [
                        { data: 'id', name: 'id' },
                        { data: 'worker_name' , name:'name' },
                        { data: 'role', name: 'role' },                     
                        { data: 'dep_name' , name:'dep_id'} ,
                        { data: 'created_at', name: 'created_at' } ,
                        {
                                "className":      "details",
                                "orderable":      false,
                                "data":           null,
                                "defaultContent": '<button class="btn btn-success" id="show">Show</button>'           }
                    ] 
            } );

My route is like below:

我的路线如下:

Route::post('/dep/fetch/workers' , 'DepsController@fetch_workers')->name('workerDepData');

My fetch_workers function inside the controller has this code:

我在控制器中的 fetch_workers 函数有以下代码:

 public function fetch_workers()
    {

        $workers =  DB::table('workers')
                    ->where('workers.dep_id' , '=' ,request('id'))
                    ->join('departaments' , 'workers.dep_id' , '=' , 'departaments.id')
                    ->select('workers.id' , 'workers.name as worker_name' , 'workers.role' , 'departaments.name as dep_name' , 'workers.created_at')
                    ->get();
        $ajaxResponse = Datatables::of($workers)->make(true);
        return $ajaxResponse;
    }

After I click the button I get an error and when I check the response from the server due to the ajax request , I see a json file which have an exception at

单击按钮后,出现错误,当我检查由于 ajax 请求而来自服务器的响应时,我看到一个 json 文件在

Symfony\Component\HttpKernel\Exception\HttpException.

Symfony\Component\HttpKernel\Exception\HttpException。

I check for this kind of exception and I saw it was due to a route using get instead of post. My route as you can see is using post so I don't understand why is this exception.

我检查了这种异常,我发现这是由于使用 get 而不是 post 的路由。如您所见,我的路线是使用 post,所以我不明白为什么会出现这种异常。

回答by Anar Bayramov

As I have mentioned in comments. Its CSRFtoken issue.

正如我在评论中提到的。它的CSRF令牌问题。

In order to fix it

为了修复它

1) You can exclude your URI for CSRF

1)您可以为CSRF排除您的URI

2) You can put csrf_token() to your ajax request.

2)您可以将 csrf_token() 放入您的 ajax 请求中。

Detailed explaination can be found here https://laravel.com/docs/5.5/csrf

详细解释可以在这里找到https://laravel.com/docs/5.5/csrf

回答by ZZA

You must include CSRF token in both blade form and post method.

您必须在刀片形式和 post 方法中包含 CSRF 令牌。

var _token = $("input[name='_token']").val();

and pass together with other data.

并与其他数据一起传递。

data: { _token:_token , etc:etc },

have fun :)

玩得开心 :)

回答by Detroit Charan

Laravel: For those who are facing with csrf issue with ajax in laravel

Laravel:对于那些在 Laravel 中使用 ajax 遇到 csrf 问题的人

enter image description here

在此处输入图片说明

<?php

if(condition){
  
   $updated_field = 'User' ;
   
  $id = $t->updated_value;

  echo '<script type="text/javascript">';
  echo '$(document).ready(function(){ 
    
  var updated_value ='.  $id .';
  //alert(updated_value);
  
  $.ajaxSetup({
   headers : { "X-CSRF-TOKEN" :jQuery(`meta[name="csrf-token"]`). attr("content")}
  });
  $.ajax({
    type:"POST",
    url : "get_username",
    data : { id: id },
    success: function(){
   console.log(data);
    }
  });

    });';
   echo '</script>';

}

?>

回答by DsRaj

In all the latest version above 5.6, you can use like this

5.6以上的所有最新版本中,你可以这样使用

<form method="POST" action="YOUR_ACTION">
    @csrf
    ...
</form>