我编写了以下代码:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname ));
app.get('/', function (req, res) {
res.sendFile('./dist/index.html');
});
app.listen(3000, function() {
console.log("Listening on port 3000");
});
这不起作用。当打开浏览器并转到“localhost:3000”时,出现错误:
path must be absolute or specify root to res.sendFile
当然,一旦我将以“app.use...”开头的行修复为:
app.use('/', express.static(__dirname + "./dist"));
然后一切正常。
您能解释一下原因吗?为“express.static”提供发送文件的直接文件夹的父文件夹路径有什么问题?
最佳答案
尝试更改顺序。而不是:
app.use('/', express.static(__dirname ));
app.get('/', function (req, res) {
res.sendFile('./dist/index.html');
});
尝试:
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, './dist/index.html'));
});
app.use('/', express.static(__dirname));
// OR:
app.use('/', express.static(path.join(__dirname, 'dist')));
加上使用path.join()
加入路径。您需要要求 path
第一:
var path = require('path');
有关提供静态文件及其原因的更多信息,请参阅此答案 path.join
很重要:
现在,你的问题不是关于 express.static
但关于res.sendFile
。当你改变express.static
到另一个文件的路径,然后是您之前想要使用 res.sendFile
发送的文件可能是由 express.static
找到的和处理程序 res.sendFile
根本没有运行。更改之前,express.static
没有找到 index.html
文件并将请求传递给下一个处理程序 - 该处理程序有一个错误 res.sendFile
调用。这就是为什么它似乎解决了错误问题,因为导致错误的代码不再被调用。
关于Node.js + Express : What do I have to serve the specific folder's path to express. 静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43233015/