使用Express提供HTML页面

12

我有一个HTML文件(privacy.html),想将其作为主页服务。我编写了以下内容:

app.get('/', (req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'})
  res.write(require('./privacy.html'))
  res.end()
})

什么有问题?
3个回答

23

这可能就是你在寻找的内容:

app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});

6
你不应该使用require来包含html。看一下express的res.sendFileexpress.static。看起来你可能想要后者,但如果你确定需要保留现有结构,前者是更灵活的选择。
这里有关于require和模块系统的更多信息
编辑:我建议你阅读我提供的链接,但我还是会给你一些代码,以便你不会使用不良技术。
完整的实现非常简单:
// Somewhere above, probably where you `require()` express and friends.
const path = require('path')

// Later on. app could also be router, etc., if you ever get that far

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'privacy.html'))
})

// If you think it's still readable, you should be able rewrite this as follows.

app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'privacy.html')))

有一些方法可以使这个更加高级(如绑定等),但是既然这个本来就能很好地工作,那么这些方法都没有必要。这个方法适用于任何 express 支持的系统,包括路径分隔符/文件系统层次结构不同的系统。


我尝试使用res.write(express.static('./privacy.html')),但似乎不起作用... - ocram
是的,但我没有目录,只有一个文件,我不想为一个文件创建一个新目录。我也尝试过 res.sendFile(path.join(__dirname, 'privacy.html')) - ocram

0

链接已损坏。 - Yigit Alparslan
没有什么问题。点赞了。所以CodeForGeek改变了一个位置,请不要纠结。 - Cody

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接