JWT认证 使用navigator.sendBeacon 请求无法自定义headers 解决方案

4,189 阅读1分钟

web项目中有个需求,在刷新页面或关闭页面时,发送 Ajax 请求,使用同步发送请求时,浏览器会弹出不可控确认弹窗,无法获知到用户是否操作了离开还是点击了取消继续留在此页面。最佳解决方案是使用 navigator.sendBeacon 发送异步请求方式,这样既无需后端做任何改变,也不影响用户体验。具体请参考底部 参考文献

熟悉JWT认证的知道有两种认证方式:

1、设置 authorization 请求头

  • Authorization: Bearer {yourtokenhere}

2、直接传参方式

聪明的朋友应该知道解决方案是什么了

bad (反例,此种方式无法完成认证)

let blob = new Blob([`room_id=${room_id}&timestamp=${param.timestamp}&sign=${sign}`], {type : 'application/x-www-form-urlencoded'});

navigator.sendBeacon(apiUrl.room_quit, blob);

good(既然无法设置headers,就使用token传参方式即可)

let blob = new Blob([`room_id=${room_id}&token=${token}&timestamp=${param.timestamp}&sign=${sign}`], {type : 'application/x-www-form-urlencoded'});

navigator.sendBeacon(apiUrl.room_quit, blob);

参考文献

如何在 Web 关闭页面时发送 Ajax 请求

【MDN】navigator.sendBeacon()