[英]How to render html page on certain path from certain directory with 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文件夾中
您通常要嘗試通過稱為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
已被刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.