javascript - Node js 上的 HTTP 服务器和 Console.log
问题描述
我是 node js 的新手并尝试通过一些示例来学习,所以我的要求是我应该在浏览器控制台模式下获得输出,我想通过 HTTP 服务器和控制台检查它,但数据只打印在浏览器页面上但没有得到任何控制台输出。
代码:
require('http').createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Data render at browser page');
console.log('print in browser console ');
}).listen(4000);
解决方案
您可以发送 HTML 响应并添加脚本标记:
/********** Node.js start ********/
/* This code is run in Node.js */
require('http').createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('' +
`<html>
<head></head>
<body>
Data render at browser page
<script>
/********** Browser start ********/
/* This code is run in the browser */
console.log('print in browser console ');
/********** Browser end ********/
</script>
</body>
</html>`);
console.log('print in Node.js engine');
}).listen(4000);
/********** Node.js end ********/
推荐阅读
- python - 创建生成器以相反的顺序读取文本文件中的每一行
- sql - 当添加/更新发生在另一个表中时,如何通过 SQL Server 中的存储过程在表中添加/更新记录
- eclipse - 忽略 .gitignore 中的所有子文件夹/文件
- javascript -
- 得到一些元素后消失
- html - 将样式应用于标签时,使样式覆盖另一种样式
- excel - 向文件夹中的所有工作簿添加新的和删除旧的 VBA
- git - “git grep
" 仅适用于 python(或任何类型的)文件? - html - CSS ul li 格式化
- python - 激活 python 虚拟环境后,输入 `python` 仍然会得到 PATH 中的版本
- c# - 发送电子邮件后,消息 ID (PR_INTERNET_MESSAGE_ID_W_TAG) 在事件处理程序中不可用