【问题标题】:Error: Cannot find module 'html' with Node.JS and Express错误:无法使用 Node.JS 和 Express 找到模块“html”
【发布时间】:2017-09-11 09:42:53
【问题描述】:

我一直在查看有关此问题的回复,但没有任何帮助。一些解决方案也给了我更多的错误。

我想要做的是使用 Node.JS 路由到不同的页面。在了解了一点 MEAN 堆栈后,我决定使用 Node、Express 和 Angular(还没有实现)。如果我尝试到任何不是“/”路线的地方,我会收到一条错误消息,提示“找不到模块 'html”。以下是有问题的代码:

//dependencies
var express = require('express');
var path = require('path');
var engines = require('consolidate')

//variables
var RUN_PORT = 8080;
var VIDEO_IN_PORT = 45679;
var CONTROL_OUT = 45678;
var app = express();

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

//index.html routing
app.get('/', function(req, res){
    res.render("index.html");
});

//robot_control.html routing
app.get('/robot_control', function(req, res){
    res.render("robot_control.html");
});

//error.html routing
app.get('/error', function(req, res){
    res.render("error.html");
});

//showing that the program is running on the RUN_PORT
app.listen(RUN_PORT, function(){
    console.log("Running on port " + RUN_PORT);
});

我在这里没有看到什么?一切似乎都很好。我在 package.json 中安装的只是 Express。我可以正常访问索引页面,但除此之外的任何其他内容都会导致该错误。

【问题讨论】:

    标签: javascript node.js express mean-stack meanjs


    【解决方案1】:

    问题是由使用res.render('SOMEFILE.html') 引起的,因为您没有告诉 Express 如何呈现带有.html 扩展名的文件。

    由于您(还)没有使用任何模板,您可以使用这个:

    // Somewhere at the top:
    const path  = require('path');
    const VIEWS = path.join(__dirname, 'views');
    ...
    
    // In your route handlers:
    res.sendFile('index.html', { root : VIEWS });
    

    如果您想开始使用模板,请看这里:http://expressjs.com/en/guide/using-template-engines.html

    【讨论】:

      猜你喜欢
      • 2013-02-03
      • 2019-01-31
      • 2014-07-24
      • 2014-11-07
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-29
      • 2018-08-05
      相关资源
      最近更新 更多