Node.js + Express:res.sendFile()处的内部异常:返回undefined,无法捕获异常,将文件传递到客户端失败(抛出404)

cgh8pdjw  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(183)

我正在使用Node.js和Express构建一个https服务器。我使用res.sendFile(path,root,onerror)将请求的文件返回给客户机。但是,sendFile()中似乎存在内部错误。脚本继续运行,没有记录任何错误,但文件没有发送(客户端抛出404)。
我可以将其作为uncaughtException捕获,但它是未定义的(我无法获得bug的详细信息/堆栈)。这可能是因为它是Node.js模块的内部错误。?

// send homepage.html from the directory the script is in
res.sendFile('homepage.html', {root: __dirname}, err=>{ if(err){ console.log(err.stack, err); process.exit(1); } }); 
// an exception occurs, but `err` in the callback is undefined. Effectively, I can't even trace the exception.

sendFile()函数本身也返回undefined,而不是一个对象。
我不知道发生了什么事。将__dirname替换为'.'不会执行任何操作。这不是一个路由问题,因为sendFile()方法返回undefined(所以这是它的内部错误)。这也不太可能是一个获取文件的权利问题。

np8igboo

np8igboo1#

你的完整代码是什么?你在使用es-module吗?

app.get('/home', (req, res) => {
  res.sendFile('homepage.html', { root: __dirname }, err => {
    if (err) {
      console.log(err.stack, err);
      process.exit(1);
    }
  });
});

显然这很有效
如果您使用的是es-module

import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

相关问题