首页 > 解决方案 > 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); 

标签: javascriptnode.js

解决方案


您可以发送 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 ********/

推荐阅读