简体   繁体   中英

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

I'm trying to create a server for my HTML application, but when I go to localhost:8080/map I get Error: Cannot find module 'HTML' . Still, the main at localhost:8080 page works fine.

My code:

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}/`)
 })

You are using EJS so you need to do this

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

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

Use the app.engine(ext, callback) method to create your own template engine. ext refers to the file extension, and callback is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.

So with that you actually make the node runtime to load the 'html' template engine and it works fine.

Please refer to this link

Also you are missing quotes on this line app.set("view engine", html); . It should be 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`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM