如何使用node.js表达从特定目录在特定路径上呈现html页面

时间:2017-02-21 01:33:37

标签: javascript html node.js express

const express = require('express');
const app = express();
var path = require('path');
app.get('/', function(req,res){
    res.sendFile(path.join(__dirname+'/login.html'));
});
app.get('/views', function(req,res){
    res.sendFile(path.join(__dirname+'/views/index.html'));
});


// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
// [END app]

渲染login.html没有任何问题。我在我的views目录中有index.html,并且很难渲染index.html。我知道应该在某个地方使用app.use并且我已经尝试了但是我不知道如何使这个工作正常所以当我输入localhost:8080 / views时,index.html应该正确弹出以及一切正常工作在views文件夹

1 个答案:

答案 0 :(得分:0)

您尝试实现的目标通常是使用express.static

这个想法非常简单:

假设您要呈现目录/views,以便/views/file1.txt发送path.join(__dirname+'/views/file1.txt')等等。

你可以简单地做

app.use('/views', express.static(path.join(__dirname, 'views')));

这适用于/views目录中的任何文件。

<小时/> 的修改

根据您使用的express版本,您可能需要查看serve-static,这是自express.static移除后的独立版本。