使用Express服务HTML

ocr*_*ram 3 node.js express

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

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

怎么了?

小智 6

这可能是您要寻找的:

app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});
Run Code Online (Sandbox Code Playgroud)

  • 这样硬编码路径分隔符被认为是不好的做法。相反,请使用[`path.join` API](https://nodejs.org/api/path.html#path_path_join_paths)创建路径。请参阅下面的我的(现在编辑的)答案。 (3认同)

Aeh*_*mlo 5

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')))
Run Code Online (Sandbox Code Playgroud)

有很多方法可以使这个更有趣(绑定等),但是当它按原样正常工作时,它们都不值得做。这将适用于任何地方express,包括在路径分隔符/文件系统层次结构不同的系统上。