404 Error: ENOENT, stat '/public/ when starting app from grunt

404 Error: ENOENT, stat '/public/ when starting app from grunt

我正在运行一个尝试使用 sedfile

提供静态 html 服务的快速应用程序
res.sendfile('/public/testform.html');

当我使用节点 app.js 启动应用程序时,它工作正常。当我尝试使用 grunt 启动应用程序时,它不起作用,它给我错误

404 错误:ENOENT,统计 '/public/testform.html'

我都试过了

  res.sendfile(__dirname+'/public/testform.html');
  res.sendfile(path.resolve('/public/testform.html'));

但我仍然没有从咕噜声中得到好运。我究竟做错了什么 ?

可能与快速静态文件服务有关。

只需将此添加到您的 app.js:

app.use('/public',express.static(path.join(__dirname, 'path-to-public/public')));

请注意 app 我指的是:var app = express(); 并注意中间件的顺序。

我不知道为什么,但我能够让它工作的唯一方法是以下

app.get('/testform', function (req, res) {
  var correctPath = path.join(__dirname, '..','/public/testform.html');
  res.sendfile(daPath);
});

__dirname inside routes 比它应该在的地方低了一层,所以我不得不向上移动一层。