首页 > 解决方案 > 没有指定默认引擎,也没有提供扩展名

问题描述

我正在尝试仅使用 html 并从我的快速服务器呈现页面。我不断收到错误

No default engine was specified and no extension was provided.

我在 app.js 中指定了目录名,并告诉服务器使用路由器中的目录名进行渲染。我不确定是什么阻碍了我?有人可以提供一些见解吗?

app.js(我删除了不相关的导入语句)

var app = express();

app.use(express.static(__dirname + '/public'));  //setting static file directory
//Store all HTML files in view folder.

module.exports = app;

这是我在页面上调用渲染的索引路由器


var express = require('express');
var router = express.Router();
const path = require('path');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('main', { title: 'Express' });
});

/* GET styles page. */
router.get('/style', function(req, res, next) {
  res.render('styles', { title: 'styles' });
});

/* GET styles page. */
router.get('/style',function(req,res){
  res.sendFile(path.join(__dirname+'/style.html'));
});





module.exports = router;

标签: javascripthtmlexpressstatic

解决方案


如果您没有像 Handlebars 这样的渲染器,res.render据我所知,您无法调用。如果您提供静态视图,则无论如何都不需要渲染器,您只需指定静态文件所在的文件夹。

这意味着在您指定静态文件夹后,您将能够通过在路径中包含文件名来访问文件。Express 的静态文件文档。您不需要路由来发送文件。

例子

代码沙盒示例

src
|- view
|  |- hello.html
|- index.js

index.js

const express = require("express");
//create a server object:
const app = express();

//Serve all files inside the view directory, path relative to where you started node
app.use(express.static("src/view/"));

app.listen(8080, function() {
  console.log("server running on 8080");
}); //the server object listens on port 8080

module.exports = app;

您现在将hello.html/hello.html路线上看到。任何其他文件也将以其名称显示。


推荐阅读