Node.js Node express app.get(“父目录”/“父目录”不工作 /core/server.js /core/index.html /core/styles.css /bin/init transpiled.js

Node.js Node express app.get(“父目录”/“父目录”不工作 /core/server.js /core/index.html /core/styles.css /bin/init transpiled.js,node.js,express,Node.js,Express,如何在localhost:8000(而不是/core)上托管index.html,其中index.html仍然可以访问相对路径。/bin/init transpiled和/styles.css?您可以像这样托管index.html文件 app.get('/', function(req, res) { res.sendFile(path.resolve(__dirname + "/index.html")); }); <script src="../bin/init-transp

如何在
localhost:8000
(而不是
/core
)上托管
index.html
,其中
index.html
仍然可以访问相对路径
。/bin/init transpiled
/styles.css

您可以像这样托管index.html文件

app.get('/', function(req, res) {
    res.sendFile(path.resolve(__dirname + "/index.html"));
});
<script src="../bin/init-transpiled.js">
您需要在服务器配置中将bin文件夹设置为静态文件夹,以便从客户端访问bin文件夹文件

app.use(express.static(path.resolve(__dirname + '/../bin')));   
然后在index.html中,您可以像这样访问您的文件

app.get('/', function(req, res) {
    res.sendFile(path.resolve(__dirname + "/index.html"));
});
<script src="../bin/init-transpiled.js">

请注意,如果索引使用
/styles.css
作为示例,则需要使用
。/core/styles.css

app.use('/', express.static(__dirname));
app.use('/', express.static(__dirname + '/../'));
app.get('/', function (req, res) {
    res.sendFile(__dirname + "/index.html");
});

使用
'/'

  • 静态承载此目录(例如,用于访问本地
    /styles.css
  • 静态承载父目录(否则无法遍历
    。/bin/
  • 作为响应发送
    index.html

  • 注意:
    '/'
    不是必需的,默认值为
    '/'
    ,您只需将中间件处理程序函数作为第一个参数编写即可


    请参见

    很抱歉,res.sendFile不使用相对路径。