我在Laravel应用程序中使用Ajax发出了一堆POST请求。
典型的请求如下所示:
$.ajax({
url: '/path/to/method',
data: {'id': id},
type: 'POST',
datatype: 'JSON',
success: function (response) {
//handle data
},
error: function (response) {
//handle error
}
});
Run Code Online (Sandbox Code Playgroud)
我已经设置了CSRF令牌,并且大多数情况下一切正常:
jQuery(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
Run Code Online (Sandbox Code Playgroud)
但是,经过长时间的中断(例如,计算机长时间处于睡眠状态),所有Ajax调用都会返回419错误,就像未设置令牌一样。重新加载页面后,一切恢复正常。这是在本地服务器上。
我该如何解决?通话前是否可以通过某种方式“更新”令牌?$.ajaxSetup每次通话前我都需要做一点吗?仅在页面加载一次就做还不够吗?
这是我的建议:
JS
//create a function to set header
function setHeader(data){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': data
}
});
}
//in first load of the page set the header
setHeader($('meta[name="csrf-token"]').attr('content'));
//create function to do the ajax request cos we need to recall it when token is expire
function runAjax(data){
$.ajax({
url: '/path/to/method',
data: {'id': id},
type: 'POST',
datatype: 'JSON',
success: function (response) {
//handle data
},
error: function (jqXHR, textStatus, errorThrown) {
if(jqXHR.status==419){//if you get 419 error which meantoken expired
refreshToken(function(){refresh the token
runAjax();//send ajax again
});
}
}
});
}
//token refresh function
function refreshToken(callback){
$.get('refresh-csrf').done(function(data){
setHeader(data);
callback(true);
});
}
//Optional: keep token updated every hour
setInterval(function(){
refreshToken(function(){
console.log("Token refreshed!");
});
}, 3600000); // 1 hour
Run Code Online (Sandbox Code Playgroud)
路线
//route to get the token
Route::get('refresh-csrf', function(){
return csrf_token();
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
1146 次 |
| 最近记录: |