簡體   English   中英

為什么在運行 nodejs express 服務器時出現錯誤:找不到模塊 'html'?

[英]Why do I get Error: Cannot find module 'html' when running nodejs express server?

我正在嘗試為我的 HTML 應用程序創建服務器,但是當我 go 到 localhost:8080/map 時,我得到Error: Cannot find module 'HTML' 盡管如此, localhost:8080 頁面的主頁面工作正常。

我的代碼:

const path = require('path');
const port = 8080;
const express = require('express');
const app = express();

app.use(express.static(path.join(__dirname, 'public')));
app.set("view engine", html);


app.get('/', (req, res) => {
    res.render('index.html')
})

app.get('/map/', (req, res) => {
    res.render('map.html')
})

var server = app.listen(8080, function () {
    console.log(`App listening at http://localhost:${server.address().port}/`)
 })

你正在使用 EJS,所以你需要這樣做

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);

使用app.engine(ext, callback)方法創建您自己的模板引擎。 ext指的是文件擴展名, callback是模板引擎function,它接受以下項目作為參數:文件的位置,選項object,以及回調ZC1C425268E68385D1AB5074C17A94。

因此,您實際上使節點運行時加載“html”模板引擎並且它工作正常。

請參考此 鏈接

此外,您在這一行app.set("view engine", html);上缺少引號。 . 它應該是app.set("view engine", "html");

 const express = require('express'); const app = express(); app.use('/', express.static(__dirname + '/')); app.get('/', function(req, res) { //res.render('index.html') //Such a static call assumes the existence of an index.html file at the call address: nodejs\node_modules\index.html }); app.get('/map', function(req, res) { res.send('Taylor Swift'); }); app.listen(8080); console.log(`App listening at http://localhost:8080/map`)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM