呈现基本的HTML视图?

318

我有一个基本的Node.js应用程序,我正在尝试使用Express框架启动它。我有一个views文件夹,其中有一个index.html文件。但是在加载网页时出现以下错误:

Error: Cannot find module 'html'

以下是我的代码。

var express = require('express');
var app = express.createServer();

app.use(express.staticProvider(__dirname + '/public'));

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

app.listen(8080, '127.0.0.1')

我在这里漏掉了什么?

31个回答

2

我试图搭建一个带有express RESTful API的angular应用程序,但多次打开这个页面却没有得到有效帮助。以下是我发现可行的方法:

app.configure(function() {
    app.use(express.static(__dirname + '/public'));         // set the static files location
    app.use(express.logger('dev'));                         // log every request to the console
    app.use(express.bodyParser());                          // pull information from html in POST
    app.use(express.methodOverride());                      // simulate DELETE and PUT
    app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
});

然后在您的api路由回调中,可以这样写:res.jsonp(users);

您的客户端框架可以处理路由。Express用于提供API。

我的主页路由看起来像这样:

app.get('/*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

2

这里是一个完整的express服务器演示文件!

https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

希望对你有所帮助!

// simple express server for HTML pages!
// ES6 style

const express = require('express');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const app = express();

let cache = [];// Array is OK!
cache[0] = fs.readFileSync( __dirname + '/index.html');
cache[1] = fs.readFileSync( __dirname + '/views/testview.html');

app.get('/', (req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.send( cache[0] );
});

app.get('/test', (req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.send( cache[1] );
});

app.listen(port, () => {
    console.log(`
        Server is running at http://${hostname}:${port}/ 
        Server hostname ${hostname} is listening on port ${port}!
    `);
});


2
res.sendFile(__dirname + '/public/login.html');

2
很遗憾的是,到了2020年,Express仍然没有添加一种在不使用响应对象的sendFile方法的情况下呈现HTML页面的方式。使用sendFile并不是问题,但以path.join(__dirname,“相对/文件路径”)的形式传递参数并不合适。为什么用户需要将__dirname与文件路径连接起来?这应该是默认完成的。为什么服务器的根目录不能默认为项目目录?此外,仅为呈现静态HTML文件安装模板依赖项也是不正确的。我不知道解决问题的正确方法,但如果我必须提供静态HTML,则会执行以下操作:
const PORT = 8154;

const express = require('express');
const app = express();

app.use(express.static('views'));

app.listen(PORT, () => {
    console.log(`Server is listening at port http://localhost:${PORT}`);
});

上面的示例假设项目结构有一个名为views的目录,并且静态HTML文件在其中。例如,假设views目录有两个HTML文件,分别命名为index.htmlabout.html,那么我们可以访问以下网址来访问它们:localhost:8153/index.html或只需使用localhost:8153/来加载index.html页面,以及localhost:8153/about.html来加载about.html。我们可以使用类似的方法来存储React/Angular应用程序中的构件,并将其配置到服务器JS中,如下所示:使用默认的dist/<project-name>目录。
app.use(express.static('dist/<project-name>'));

2

index.js

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));


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


app.listen(3400, () => {
    console.log('Server is running at port 3400');
})

将您的index.html文件放在public文件夹中。
<!DOCTYPE html>
<html>
<head>
    <title>Render index html file</title>
</head>
<body>
    <h1> I am from public/index.html </h1>
</body>
</html>

现在在终端中运行以下代码

node index.js


1
对于纯HTML,您不需要任何npm包或中间件,只需使用以下代码:
app.get('/', function(req, res) {
    res.sendFile('index.html');
});

0
请在 server.js 中包含。
var express = require("express");
var app     = express();
var path    = require("path");


app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

0

如果您正在尝试提供一个已经包含所有内容的HTML文件,则不需要对其进行“渲染”,只需要“提供”即可。渲染是指在将页面发送到浏览器之前,服务器更新或注入内容,这需要像ejs一样的其他依赖项,就像其他答案所示。

如果您只想根据用户请求直接将浏览器定向到文件,则应像这样使用res.sendFile()

const express = require('express');
const app = express();
var port = process.env.PORT || 3000; //Whichever port you want to run on
app.use(express.static('./folder_with_html')); //This ensures local references to cs and js files work

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/folder_with_html/index.html');
});

app.listen(port, () => console.log("lifted app; listening on port " + port));

这样就不需要除了express之外的其他依赖项。如果您只想让服务器发送已经创建的HTML文件,则上述方法是一种非常轻量级的方法。

0

我想允许 Express 路由处理对“/”的请求,而之前这些请求是由静态中间件处理的。这将使我能够呈现常规版本的 index.html 或加载经过连接和压缩的 JS 和 CSS 版本,具体取决于应用程序设置。受 Andrew Homeyer's answer 的启发,我决定将我的 HTML 文件 - 未修改的 - 拖到一个视图文件夹中,并像这样配置 Express

   app.engine('html', swig.renderFile);
   app.set('view engine', 'html');
   app.set('views', __dirname + '/views');  

然后创建了一个路由处理程序,如下所示

 app.route('/')
        .get(function(req, res){
            if(config.useConcatendatedFiles){
                return res.render('index-dist');
            }
            res.render('index');       
        });

这个效果还不错。


-1

我通常使用这个

app.configure(function() {
    app.use(express.static(__dirname + '/web'));
});

要小心,因为这会共享/web目录中的所有内容。

希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接