我有一个像这样的目录结构:
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的新手。
答案 0 :(得分:2)
您可以使用express.static("")
来提供静态文件。
示例:
const express = require("express");
const app = express();
const server = app.listen(PORT, () => {});
app.use(express.static("./web"));
这将使Web文件夹中的所有内容公开,并且可以在localhost:PORT/html/index.html
上找到index.html文件。
这也会正确地为您的js
和css
文件提供服务
要单独提供html,您需要使用绝对路径:
app.get('/web',function(req,res)
{
res.sendFile(path.join(__dirname, './web/html/index.html'));
})
记住要包含const path = require(path)