Node js 上的 HTTP 服务器和 Console.log

far*_*raz 2 javascript node.js

我是 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); 
Run Code Online (Sandbox Code Playgroud)

jab*_*baa 5

您可以发送 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 ********/
Run Code Online (Sandbox Code Playgroud)