问题描述
我正在使用Laravel的Yajra数据表来显示带有按钮操作的文件列表。
我使用post方法使用此下载按钮,以检查授权是否允许用户下载该当前文件。
我已经检查了页面,并且确实看到了CSRF令牌。但是,Laravel仍然会抛出419错误。
这是一段控制器代码,我在其中使用CSRF令牌在Form内生成一个发布按钮:
return DataTables::of($mediaItems)
//...
//ACTION BUTTONS
->addColumn('action',function (Media $file){
$button = '<form method="post" action="'.route('download.file',['media'=>$file]).'">
<meta name="csrf-token" content="'.csrf_token().'">
<button type="submit" name="download" class="btn btn-info" title="Download file"><i class="fas fa-file-download"></i></button>
</form> ';
return $button;
})
->toJson();
就在视图上Web浏览器的inspect元素上,这就是我所看到的:
<form method="post" action="http://myApp.local/file/download/z271dd4u-b0a2-44f6-a0a5-cmxd33de3e15">
<meta name="csrf-token" content="O02W6Fu9BoW1futzAL06BbFmDfsS8lgmmx4Vd05A">
<button type="submit" name="download" class="btn btn-info" title="Download"><i class="fas fa-file-download"></i></button>
</form>
当我单击下载按钮时,为什么仍然出现419 页面过期错误?
解决方法
您必须传递csrf令牌作为值。当您在表单中使用@csrf
并检查表单时,您会发现它会生成一个名为_token
的隐藏输入字段,其值为csrf token。您不能使用meta标签通过请求传递值。因此,请使用隐藏的输入字段。
<input type="hidden" name="_token" value=" '.csrf_token().' ">