溫故而知新 前端日志上傳新姿勢 navigator.sendBeacon(信標)


原文地址:https://mp.weixin.qq.com/s/-moAfEZicrFmun4qfWLdOQ

 

簡單示例js:

var data = JSON.stringify({
  name: 'Berwin'
});
navigator.sendBeacon('http://localhost:80/index.php', data)

 

簡單php示例:

由於是信標發送的 POST 請求,並且是 "text/plain" 數據類型,所以適合用 $GLOBALS['HTTP_RAW_POST_DATA'] 接受。

順便一提,最好不要使用GET方式請求類似: navigator.sendBeacon('http://localhost:80/index.php?a=123') ,不太適合也不是正確的套路。

<?php 

header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:x-requested-with,content-type'); 

function WriteLog($msg,$module = null,$logLevel = "DEBUG")
{
    $filepath = "./log/";
    if(!is_dir($filepath)) mkdir($filepath,'0777');
    $MyLogFile = @fopen($filepath.date("Y-m-d").".txt",'a+');

    $time = date("Y-m-d H:i:s");
    if(isset($module)){$module =  sprintf("\r\n歸屬模塊:".$module."\r\n");}
    $logLine = "\r\n-------------------------------  $time -------------------------------\r\n";
    $logLine .= $module;
    $logLine .= "\r\n異常信息:$msg\r\n";
    $logLine .= "\r\n錯誤等級:$logLevel\r\n";
    fwrite($MyLogFile,$logLine);
}

WriteLog($GLOBALS['HTTP_RAW_POST_DATA']);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM