gpt4 book ai didi

Node.js + Express : What do I have to serve the specific folder's path to express. 静态?

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:39 25 4
gpt4 key购买 nike

我编写了以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com