node.js - 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 模块。我做错了什么?任何帮助表示赞赏。
解决方案
我认为你不能像那样抓住它,因为 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 运行相同的代码时它运行良好。
推荐阅读
- java - 在提交时获取请求参数数据
- json - 无法使用 Jackson ObjectMapper 将 Json 序列化为 Java 对象
- javascript - 我可以制作一个按钮,将计算销售佣金的列添加到我的表中吗
- angular - RxJs 条件去抖动和采样
- sql - How to calculate time difference between rows
- java - 如何计算饼图中显示的日期与当前日期之间的差异
- rust - 为什么我不能通过`use`导入`std :: assert`,而它适用于std中的其他宏?
- javascript - 如何计算圆形路径上的点?(中心已知)
- javascript - 将 Javascript 变量值发送到电子邮件
- angular - Handsontable numbro 库中的错误,仅在生产版本中发生