简体   繁体   English

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

[英]HTTP Server and Console.log at Node js

I am new to node js and trying to learn with a few examples, so my requirement is I should get output in browser console mode, I want to check it via HTTP server as well as in console, but data is printed only on browser page but didn't get any console output.我是 node js 的新手,并试图通过几个例子来学习,所以我的要求是我应该在浏览器控制台模式下获得输出,我想通过 HTTP 服务器和控制台检查它,但数据只打印在浏览器页面上但没有得到任何控制台输出。

Code:代码:

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); 

You can send a HTML response and add a script tag:您可以发送 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 ********/

Node Js 不在浏览器中运行,因此您看不到任何console.log()输出到浏览器控制台,而是会显示在终端中。

It's a bit confusing if you are using node.js for the first time because it runs on the server instead of the client browser.如果您是第一次使用 node.js,这有点令人困惑,因为它运行在服务器而不是客户端浏览器上。

Having said that, is actually now possible to pipe your node console output to the browser console.话虽如此,实际上现在可以将您的节点控制台输出通过管道传输到浏览器控制台。 Please check out this github repo connect-browser-logger on github请在 github 上查看这个 github repo connect-browser-logger

You can also use NodeMonkey as mentioned here - Output to Chrome console from Node.js您还可以使用NodeMonkey提到的NodeMonkey - 从 Node.js 输出到 Chrome 控制台

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM