【问题标题】:node.js client side errors not showing in consolenode.js 客户端错误未显示在控制台中
【发布时间】:2021-12-02 01:24:50
【问题描述】:

我在学校的 Chromebook 上,开发者工具被禁用。我有时在 node.js 上编码,有服务器端和客户端代码。但是,由于开发人员工具被禁用,我无法在客户端检查错误,只发现它有时只是停止工作而没有任何错误线索。在编写客户端代码时,我经常遇到这个问题。

我如何仅通过可视化访问 node.js 控制台以及 express 和 socket.io 来检测和识别错误?

例如,

const express=require("express");
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.use(
  '/client', 
  express.static(__dirname + '/client')
);
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/client/index.html');
  console.log("sending site");
});
http.listen(3000, () => {
  console.log('listening on *:3000 (http.listen)');
});

io.on('connection', (socket) => {
  socket.emit("ERRORNOW",26);
});
//"<script src="/socket.io/socket.io.js"></script>" assumed to be in HTML file
var socket=io();

socket.on("ERRORNOW",()=>{
  if("this doesnt have an ending curlybracket){

  //} 
  //this is the error it doesnt have the ending curly bracket, 
  //but it doesn't show in the node.js console 
  //(at least on browser IDEs like repl.it), 
  //and debugging without the developer tools 
  //can be infuriating to say the least
});

问题是如何在没有开发人员工具的情况下在基于 Web 的 IDE 上识别 node.js 客户端错误?

【问题讨论】:

    标签: javascript node.js express try-catch error-checking


    【解决方案1】:

    我前段时间就遇到过这个问题,由于学校 Chromebook 上缺乏开发者工具,我自己找到了解决方案,但我只是想也许我也应该把它放在这里。

    我的解决方案尽可能简单,就是使用 try-catch 语句并将错误发送到 node.js 控制台。花了一段时间才弄清楚...

    因此,如果您还没有它,则需要一个函数,当从客户端触发时,该函数可以在 io.on("connection",()=&gt;{}); 事物内部将某些内容记录到控制台中,如下所示:

    io.on("connection",()=>{
      socket.on("log", input=>{
        console.log(input);
      });
    });
    

    例如,如果所有内容都由一个触发速度非常快的函数运行(具体但与我相关,因为我制作网页游戏),或者只是从某个函数运行,您可以在一个函数内运行它试试 catch,像这样:

    //"<script src="/socket.io/socket.io.js"></script>" assumed to be in HTML file
    var socket=io();
    try{
    socket.on("ERRORNOW",()=>{
      try{
      if("this doesnt have an ending curlybracket){
    
      //} 
      }catch(error){
        socket.emit("log",error);
      }
    });
    }catch(error){
      socket.emit("log",error);
    }
    

    因此,现在,通过这个简单的解决方案,您可以停止注释掉 90% 的代码,以发现一个导致其停止工作的错误,同时通过不小心注释掉帮助它首先工作的部分来进一步破坏它!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-19
      • 2016-02-11
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 1970-01-01
      相关资源
      最近更新 更多