首页 > 解决方案 > Node.js 不处理 express 中的错误

问题描述

我有这个代码:

const express = require("express");
const app = express();

var meetings = [];

app.use("/static", express.static("public/"))
app.use("/index.html?", function(request, response, next) {
    response.redirect("/");
})

app.get("/", function(request, response) {
    response.sendFile(__dirname + "/pages/index.html");
})

try {
    app.listen(80);
} catch(e) {
    console.log("Can't run on port 80. Please, run me as a sudo!");
}

当我运行它时,我得到了这个错误:

Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1361:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EACCES',
  errno: -13,
  syscall: 'listen',
  address: '0.0.0.0',
  port: 80
}

Node.js v17.0.1

当我以 sudo 运行它时,它找不到 express 模块。我做错了什么?任何帮助表示赞赏。

标签: node.jsexpress

解决方案


我认为你不能像那样抓住它,因为 app.listen() 总是返回一个 <net.Server> 实例。要在此实例上捕获错误,您应该查找错误事件。所以,这就是你要抓住它的方式。

const express = require("express");
const app = express();

var meetings = [];

app.use("/static", express.static("public/"))
app.use("/index.html?", function(request, response, next) {
    response.redirect("/");
})

app.get("/", function(request, response) {
    response.sendFile(__dirname + "/pages/index.html");
})


app.listen(80).on(error => { 
  if (error.code === "EACCESS") {
    console.log("Can't run on port 80. Please, run me as a sudo!");
  }
});
   

至于为什么找不到express,我猜如果你用sudo运行它,它会寻找全局安装的模块。但这只是一个猜测,因为当我在我的机器上使用 sudo 运行相同的代码时它运行良好。


推荐阅读