【问题标题】:Node.js serve html filesNode.js 提供 html 文件
【发布时间】:2019-05-26 16:12:48
【问题描述】:

我有一个这样的目录结构:

    server
       code
         app.js
         web
           html
               index.html
           css
               index.css
           scripts
               index.js

我的 app.js 代码正在尝试提供 html 文件 index.html 但显示错误 这是代码:

    app.get('/web',function(req,res) 
    {
        res.sendFile('../web/html/index.html');
    })

传递给 sendFile() 的路径并使其正常工作,以便 html 文件在运行时也能找到脚本文件和 css ?

我是 node.js 的新手。

【问题讨论】:

  • 试试res.sendFile('./web/html/index.html')
  • @Jhecht 我试过你的答案,但我得到以下输出:> TypeError: path must be absolute or specified root to res.sendFile
  • 然后试试res.sendFile('./web/html/index.html', { root : __dirname })

标签: javascript html node.js web backend


【解决方案1】:

您可以使用express.static("") 提供静态文件。 示例:

const express = require("express");
const app = express();
const server = app.listen(PORT, () => {});
app.use(express.static("./web"));

这将使 web 文件夹中的所有内容都公开,并且 index.html 文件可以在 localhost:PORT/html/index.html 找到 这也将正确地为您的 jscss 文件提供服务

要单独提供 html,您需要使用绝对路径:

app.get('/web',function(req,res) 
{
    res.sendFile(path.join(__dirname, './web/html/index.html'));
})

记得添加const path = require(path)

【讨论】:

  • 快速评论 -- 根据上面的目录结构,看起来web/app.js 在同一个文件夹中。除非 OP 想通过屏幕截图澄清那部分。
猜你喜欢
  • 2018-07-02
  • 2023-03-11
  • 2012-01-17
  • 2015-04-27
  • 2017-04-01
  • 1970-01-01
  • 2013-03-06
  • 2013-10-19
  • 2014-07-20
相关资源
最近更新 更多