【问题标题】:Node.js doesn't handle an error in expressNode.js 不处理 express 中的错误
【发布时间】:2021-12-23 22:02:33
【问题描述】:

我有这个代码:

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.js express


【解决方案1】:

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

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 运行相同的代码时它运行良好。

【讨论】:

    猜你喜欢
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2012-03-02
    • 1970-01-01
    • 2016-12-29
    • 2015-09-24
    • 2012-02-22
    相关资源
    最近更新 更多