Laravel 419错误 -ajax请求 错误解决办法(CSRF验证)

两种解决办法。选择适合自己的。

第一种解决方法

适用于可以把js写在不被laravel框架渲染的js文件中的操作

1.在页面上添加 

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

2.然后在页面的script标签中添加

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

第二种解决方法

适用于改部分js可以实际被laravel框架解析的操作

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

3.如果你提交的页面是html的form页面的话,

你只需要在你的form表单里面填写上下面的一段就行啦

<form method="POST" action="/profile">
    {{ csrf_field() }}
    ...
</form>

4.如果你是在页面里面设置了ajax的请求

你只需要在页面的ajax请求里面设置_token即可,

// 封装提交的记录的函数
    function sendLog(type){
        $.ajax({
            type: 'POST',
            url: '/log',
            data: {'share_type': type, 'url_info': shareLink, 'invitation_code''{{$invitation_code}}''_token':'{{csrf_token()}}'},
            dataType: 'json',
            success: function($rtn){
                console.log($rtn);
            }
        });
    }

 

两种解决办法。选择适合自己的。

第一种解决方法

适用于可以把js写在不被laravel框架渲染的js文件中的操作

1.在页面上添加 

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

2.然后在页面的script标签中添加 

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

第二种解决方法

适用于改部分js可以实际被laravel框架解析的操作

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

3.如果你提交的页面是html的form页面的话,

你只需要在你的form表单里面填写上下面的一段就行啦

1
2
3
4
<form method="POST" action="/profile">
    @csrf
    ...
</form>

或者

1
2
3
4
<form method="POST" action="/profile">
    {{ csrf_field() }}
    ...
</form>

4.如果你是在页面里面设置了ajax的请求

你只需要在页面的ajax请求里面设置_token即可,

1
2
3
4
5
6
7
8
9
10
11
12
// 封装提交的记录的函数
    function sendLog(type){
        $.ajax({
            type: 'POST',
            url: '/log',
            data: {'share_type': type, 'url_info': shareLink, 'invitation_code''{{$invitation_code}}''_token':'{{csrf_token()}}'},
            dataType: 'json',
            success: function($rtn){
                console.log($rtn);
            }
        });
    }
原文地址:https://www.cnblogs.com/seanpan/p/11591903.html