我有一个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)
您require不习惯包含 html。看看 express 的res.sendFile和express.static。看起来您可能想要后者,但如果您确定想要拥有的结构,则前者更灵活。
编辑:我敦促您阅读我提供的链接,但无论如何我都会给您一些代码以供您使用,这样您就不会最终使用不良技术。
完整的实现非常简单:
// 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,包括在路径分隔符/文件系统层次结构不同的系统上。
| 归档时间: |
|
| 查看次数: |
5807 次 |
| 最近记录: |