我正在尝试编写一个小型 API 记录器作为 Express 中间件。记录器从 req 和 res 中收集各种信息,然后将 JSON 文件保存到磁盘以供以后读取。
这是我当前存储日志的功能。
function store(req, res, next) {
init();
const log = {
request_url: req.hostname,
request_body: req.body,
request_method: req.method,
request_headers: req.headers,
api_endpoint: req.baseUrl,
timestamp: moment().format('x')
};
res.on('finish', () => {
log.response_body = res.body;
log.response_status = res.statusCode;
global.enoch_logs.push(log);
fs.writeFile(`./logs/${ moment().format('x') }.json`, JSON.stringify(log), (err) => (err) ? console.log(err) : null);
});
next();
}
Run Code Online (Sandbox Code Playgroud)
问题是 res.body 总是空的。我尝试了几种不同的方法来捕获响应正文,但似乎没有任何效果。
我哪里错了?
我最近的任务是清理我们的 GTM 标签。我注意到很多标签通过使用 JS 将它们注入到 DOM 中来包含远程脚本,例如:
var head = document.getElementsByTagName('head')[0]
var js = document.createElement('script');
js.src = 'https://cdn.somewhere.com/script.js';
head.appendChild(js);
Run Code Online (Sandbox Code Playgroud)
人们这样做而不是仅仅使用它有什么具体的原因吗?
<script type="text/javascript" src="https://cdn.somewhere.com/script.js" async></script>
Run Code Online (Sandbox Code Playgroud)
第一种方式有什么好处?有没有更好的方法来处理外部脚本?