我有一个HTML文件(privacy.html),想将其作为主页服务。我编写了以下内容:
app.get('/', (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'})
res.write(require('./privacy.html'))
res.end()
})
什么有问题?
这可能就是你在寻找的内容:
app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});
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')))
有一些方法可以使这个更加高级(如绑定等),但是既然这个本来就能很好地工作,那么这些方法都没有必要。这个方法适用于任何 express
支持的系统,包括路径分隔符/文件系统层次结构不同的系统。
app.get('/', function(req, res){
res.sendFile(__dirname + 'privacy.html');
});
res.write(express.static('./privacy.html'))
,但似乎不起作用... - ocramres.sendFile(path.join(__dirname, 'privacy.html'))
。 - ocram