【发布时间】:2020-09-20 19:00:11
【问题描述】:
我有这个 JavaScript 文件,它每 8 秒运行一次,调用路由 /ajax?act=notifications_show。我注意到在某些页面中,javascript 文件可以正常工作,但是在访问某些页面时会显示错误,例如CSRF token mismatch。我不确定为什么会发生这种情况,但页面的布局与我扩展的相同。
请注意,我已经为每个布局添加了<meta name="_token" content="{{ csrf_token() }}"/>
Notification.js
function get_notifications(){
$.ajax({
method: "POST",
url: window.location.origin + "/ajax?act=notifications_show",
}).done(function( d ) {
console.log("d: "+ d);
// n = jQuery.parseJSON(d); //if error abort all commands below
// console.log("n: "+ n);
// //console.log(n.qqq);
// $('#header_notification_bar').html(n.notification);
// //alert(n.qqq);
// if(n.has_noti == 1){
// toastr.info('<div><a href="#" onclick="toggle_comments('+n.id+')">'+n.noti_msg+' from '+n.noti_from+'</a></div>');
// }
});
}
function toggle_comments(id){
$('body').toggleClass('page-quick-sidebar-open');
$('#msg_contents').html('');
get_chat_area(id);
get_comments(id);
}
window.onload = function(e){
$('.dropdown-quick-sidebar-toggler').click(function (e) {
$('body').toggleClass('page-quick-sidebar-open');
$('#msg_contents').html('');
get_chat_area(this.id);
get_comments(this.id);
});
setInterval(get_notifications, 8000);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
显示错误
message: "CSRF token mismatch." trace: [{,…}, {file: "C:\xampp7\htdocs\vms\app\Exceptions\Handler.php", line: 53, function: "render",…},…]
我的问题是: 为什么错误出现在某些页面上,但在其他页面上有效? 令牌不匹配时如何解决此问题?
【问题讨论】:
-
这是 POST 路由有什么原因吗?
-
重新生成你的令牌
-
@lagbox 老实说,这个项目是纯 php 代码,只是交给我。我只将原始 PHP 文件转换为 laravel,所以有些代码我不确定他们为什么要这样实现。
-
@kingneo 我是为每个
window.load重新生成令牌还是仅在出现 csrf 令牌不匹配等错误时重新生成令牌? -
生成你的项目密钥清除缓存
标签: javascript ajax laravel