渲染基本的 HTML 视图?

发布于 2024-10-09 11:01:29 字数 466 浏览 8 评论 0原文

我有一个基本的 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')

我在这里缺少什么?

I have a basic Node.js app that I am trying to get off the ground using the Express framework. I have a views folder where I have an index.html file. But I receive the following error when loading the web page:

Error: Cannot find module 'html'

Below is my code.

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')

What am I missing here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

梦在深巷 2024-10-16 11:01:29

你可以让jade包含一个纯HTML页面:

在views/index.jade中

include plain.html

,在views/plain.html中

<!DOCTYPE html>
...

,app.js仍然可以只渲染jade:

res.render(index)

You can have jade include a plain HTML page:

in views/index.jade

include plain.html

in views/plain.html

<!DOCTYPE html>
...

and app.js can still just render jade:

res.render(index)
故人爱我别走 2024-10-16 11:01:29

其中许多答案都已过时。

使用express 3.0.0和3.1.0,可以执行以下操作:

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

请参阅下面的注释,了解express 3.4+的替代语法和注意事项:

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

然后您可以执行类似的操作:

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

这假设您的视图位于 views 子文件夹中,并且您已经安装了 ejs 节点模块。如果没有,请在 Node 控制台上运行以下命令:

npm install ejs --save

Many of these answers are out of date.

Using express 3.0.0 and 3.1.0, the following works:

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

See the comments below for alternative syntax and caveats for express 3.4+:

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

Then you can do something like:

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

This assumes you have your views in the views subfolder, and that you have installed the ejs node module. If not, run the following on a Node console:

npm install ejs --save
困倦 2024-10-16 11:01:29

来自 Express.js 指南:查看渲染

视图文件名采用Express.ENGINE 形式,其中ENGINE 是所需模块的名称。 例如,视图layout.ejs将告诉视图系统require('ejs'),正在加载的模块必须导出方法 exports.render(str, options) 符合 Express,但是 app.register() 可用于将引擎映射到文件扩展名,因此例如 foo.html 可以由 jade 渲染。

因此,要么创建自己的简单渲染器,要么只使用jade:

 app.register('.html', require('jade'));

更多关于app.register

请注意,在 Express 3 中,此方法已重命名为 app.engine

From the Express.js Guide: View Rendering

View filenames take the form Express.ENGINE, where ENGINE is the name of the module that will be required. For example the view layout.ejs will tell the view system to require('ejs'), the module being loaded must export the method exports.render(str, options) to comply with Express, however app.register() can be used to map engines to file extensions, so that for example foo.html can be rendered by jade.

So either you create your own simple renderer or you just use jade:

 app.register('.html', require('jade'));

More about app.register.

Note that in Express 3, this method is renamed app.engine

鹿! 2024-10-16 11:01:29

您还可以读取 HTML 文件并将其发送:

app.get('/', (req, res) => {
    fs.readFile(__dirname + '/public/index.html', 'utf8', (err, text) => {
        res.send(text);
    });
});

You could also read the HTML file and send it:

app.get('/', (req, res) => {
    fs.readFile(__dirname + '/public/index.html', 'utf8', (err, text) => {
        res.send(text);
    });
});
美人迟暮 2024-10-16 11:01:29

试试这个。它对我有用。

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

  // make a custom html template
  app.register('.html', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });
});

....

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

try this. it works for me.

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

  // make a custom html template
  app.register('.html', {
    compile: function(str, options){
      return function(locals){
        return str;
      };
    }
  });
});

....

app.get('/', function(req, res){
  res.render("index.html");
});
嘿嘿嘿 2024-10-16 11:01:29
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
玩世 2024-10-16 11:01:29

如果您使用的是 express@~3.0.0,请将示例中的以下行更改

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

为类似这样的内容:

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

我按照 express api 页面 它的工作方式就像魅力一样。通过该设置,您无需编写额外的代码,因此可以轻松用于微生产或测试。

完整代码如下:

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

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

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

app.listen(8080, '127.0.0.1')

If you're using express@~3.0.0 change the line below from your example:

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

to something like this:

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

I made it as described on express api page and it works like charm. With that setup you don't have to write additional code so it becomes easy enough to use for your micro production or testing.

Full code listed below:

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

app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));

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

app.listen(8080, '127.0.0.1')
停顿的约定 2024-10-16 11:01:29

我在 express 3.Xnode 0.6.16 中也遇到了同样的问题。上述解决方案不适用于最新版本 express 3.x。他们删除了 app.register 方法并添加了 app.engine 方法。如果您尝试上述解决方案,您可能会遇到以下错误。

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'register'
    at Function.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:37:5)
    at Function.configure (/home/user1/ArunKumar/firstExpress/node_modules/express/lib/application.js:399:61)
    at Object.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:22:5)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

摆脱错误消息。将以下行添加到您的 app.configure 函数

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

注意:您必须安装 ejs 模板引擎

npm install -g ejs

示例:

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

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

....

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

注意: 最简单的解决方案是使用ejs 模板作为视图引擎。在那里,您可以在 *.ejs 视图文件中编写原始 HTML。

I also faced the same issue in express 3.X and node 0.6.16. The above given solution will not work for latest version express 3.x. They removed the app.register method and added app.engine method. If you tried the above solution you may end up with the following error.

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'register'
    at Function.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:37:5)
    at Function.configure (/home/user1/ArunKumar/firstExpress/node_modules/express/lib/application.js:399:61)
    at Object.<anonymous> (/home/user1/ArunKumar/firstExpress/app.js:22:5)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

To get rid of the error message. Add the following line to your app.configure function

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

Note: you have to install ejs template engine

npm install -g ejs

Example:

app.configure(function(){

  .....

  // disable layout
  app.set("view options", {layout: false});

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

....

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

Note: The simplest solution is to use ejs template as view engine. There you can write raw HTML in *.ejs view files.

傲影 2024-10-16 11:01:29

文件夹结构:

.
├── index.html
├── node_modules
│   ├──{...}
└── server.js

server.js

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

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

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

app.listen(8882, '127.0.0.1')

index.html

<!DOCTYPE html>
<html>
<body>

<div> hello world </div>

</body>
</html>

输出:

hello world

folder structure:

.
├── index.html
├── node_modules
│   ├──{...}
└── server.js

server.js

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

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

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

app.listen(8882, '127.0.0.1')

index.html

<!DOCTYPE html>
<html>
<body>

<div> hello world </div>

</body>
</html>

output:

hello world

〗斷ホ乔殘χμё〖 2024-10-16 11:01:29

如果你想渲染 HTML 文件,你可以使用 sendFile() 方法,而不使用任何模板引擎。

const express =  require("express")
const path = require("path")
const app = express()
app.get("/",(req,res)=>{
    res.sendFile(**path.join(__dirname, 'htmlfiles\\index.html')**)
})
app.listen(8000,()=>{
    console.log("server is running at Port 8000");
})

我在 htmlfile 中有一个 HTML 文件,所以我使用路径模块来渲染 index.html path 是节点中的默认模块。如果您的文件存在于刚刚

res.sendFile(path.join(__dirname, 'htmlfiles\\index.html'))

app.get() 中使用的根文件夹中,它将起作用

If you want to render HTML file you can use sendFile() method without using any template engine

const express =  require("express")
const path = require("path")
const app = express()
app.get("/",(req,res)=>{
    res.sendFile(**path.join(__dirname, 'htmlfiles\\index.html')**)
})
app.listen(8000,()=>{
    console.log("server is running at Port 8000");
})

I have an HTML file inside htmlfile so I used path module to render index.html path is default module in node. if your file is present in root folder just used

res.sendFile(path.join(__dirname, 'htmlfiles\\index.html'))

inside app.get() it will work

滥情空心 2024-10-16 11:01:29

如果您不必使用views目录,只需将html文件移动到下面的public目录即可。

然后,将此行添加到 app.configure 而不是“/views”中。

server.use(express.static(__dirname + '/public'));

If you don't have to use the views directory, Simply move html files to the public directory below.

and then, add this line into app.configure instead of '/views'.

server.use(express.static(__dirname + '/public'));
强辩 2024-10-16 11:01:29

对于我的项目,我创建了以下结构:

index.js
css/
    reset.css
html/
    index.html

此代码为 / 请求提供 index.html,为 /css/reset.css 请求提供 reset.css。足够简单,最好的部分是它会自动添加缓存标头

var express = require('express'),
    server = express();

server.configure(function () {
    server.use('/css', express.static(__dirname + '/css'));
    server.use(express.static(__dirname + '/html'));
});

server.listen(1337);

For my project I have created this structure:

index.js
css/
    reset.css
html/
    index.html

This code serves index.html for / requests, and reset.css for /css/reset.css requests. Simple enough, and the best part is that it automatically adds cache headers.

var express = require('express'),
    server = express();

server.configure(function () {
    server.use('/css', express.static(__dirname + '/css'));
    server.use(express.static(__dirname + '/html'));
});

server.listen(1337);
相对绾红妆 2024-10-16 11:01:29

要在节点中渲染 Html 页面,请尝试以下操作,

app.set('views', __dirname + '/views');

app.engine('html', require('ejs').renderFile);
  • 您需要通过 npm 安装 ejs 模块,如下所示:

     npm install ejs --save
    

To render Html page in node try the following,

app.set('views', __dirname + '/views');

app.engine('html', require('ejs').renderFile);
  • You need to install ejs module through npm like:

       npm install ejs --save
    
梨涡 2024-10-16 11:01:29

使用 Express 4.0.0,您唯一要做的就是注释掉 app.js 中的 2 行:

/* app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade'); */ //or whatever the templating engine is.

然后将静态文件放入 /public 目录中。示例:/public/index.html

With Express 4.0.0, the only thing you have to do is comment out 2 lines in app.js:

/* app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade'); */ //or whatever the templating engine is.

And then drop your static file into the /public directory. Example: /public/index.html

轻拂→两袖风尘 2024-10-16 11:01:29

Express 4.x

发送.html 文件,没有模板引擎...

//...
// Node modules
const path = require('path')
//...
// Set path to views directory
app.set('views', path.join(__dirname, 'views'))
/**
 * App routes
 */
app.get('/', (req, res) => {
  res.sendFile('index.html', { root: app.get('views') })
})
//...
.
├── node_modules
│
├── views
│   ├──index.html
└── app.js

Express 4.x

Send .html files, no template engine...

//...
// Node modules
const path = require('path')
//...
// Set path to views directory
app.set('views', path.join(__dirname, 'views'))
/**
 * App routes
 */
app.get('/', (req, res) => {
  res.sendFile('index.html', { root: app.get('views') })
})
//...
.
├── node_modules
│
├── views
│   ├──index.html
└── app.js
顾挽 2024-10-16 11:01:29

我添加了下面 2 行,它对我有用

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

I added below 2 line and it work for me

    app.set('view engine', 'html');
    app.engine('html', require('ejs').renderFile);
温折酒 2024-10-16 11:01:29

尝试 Express 路线中的 res.sendFile() 函数。

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.
});

app.get('/about',function(req,res){
  res.sendFile(path.join(__dirname+'/about.html'));
});

app.get('/sitemap',function(req,res){
  res.sendFile(path.join(__dirname+'/sitemap.html'));
});

app.listen(3000);

console.log("Running at Port 3000");

阅读此处:http://codeforgeek.com/2015/01/render-html -文件-expressjs/

Try res.sendFile() function in Express routes.

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.
});

app.get('/about',function(req,res){
  res.sendFile(path.join(__dirname+'/about.html'));
});

app.get('/sitemap',function(req,res){
  res.sendFile(path.join(__dirname+'/sitemap.html'));
});

app.listen(3000);

console.log("Running at Port 3000");

Read here : http://codeforgeek.com/2015/01/render-html-file-expressjs/

天赋异禀 2024-10-16 11:01:29

我不想依赖 ejs 来简单地交付 HTML 文件,所以我自己编写了这个微型渲染器:

const Promise = require( "bluebird" );
const fs      = Promise.promisifyAll( require( "fs" ) );

app.set( "view engine", "html" );
app.engine( ".html", ( filename, request, done ) => {
    fs.readFileAsync( filename, "utf-8" )
        .then( html => done( null, html ) )
        .catch( done );
} );

I didn't want to depend on ejs for simply delivering an HTML file, so I simply wrote the tiny renderer myself:

const Promise = require( "bluebird" );
const fs      = Promise.promisifyAll( require( "fs" ) );

app.set( "view engine", "html" );
app.engine( ".html", ( filename, request, done ) => {
    fs.readFileAsync( filename, "utf-8" )
        .then( html => done( null, html ) )
        .catch( done );
} );
他是夢罘是命 2024-10-16 11:01:29

非常遗憾的是,大约到了 2020 年,express 仍然没有添加一种不使用 response 对象的 sendFile 方法来渲染 HTML 页面的方法。使用 sendFile 不是问题,但以 path.join(__dirname, 'relative/path/to/file') 的形式向其传递参数感觉不正确。为什么用户应该将 __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 目录有两个名为 index.htmlabout.html 的 HTML 文件,那么要访问它们,我们可以访问:localhost:8153/index.html 或仅 localhost:8153/ 加载 index.html 页面和 localhost:8153 /about.html 加载 about.html。我们可以使用类似的方法来服务 React/Angular 应用程序,方法是将工件存储在 views 目录中,或者仅使用默认的 dist/ 目录,在服务器js中配置如下:

app.use(express.static('dist/<project-name>'));

It is very sad that it is about 2020 still express hasn't added a way to render an HTML page without using sendFile method of the response object. Using sendFile is not a problem but passing argument to it in the form of path.join(__dirname, 'relative/path/to/file') doesn't feel right. Why should a user join __dirname to the file path? It should be done by default. Why can't the root of the server be by defalut the project directory? Also, installing a templating dependency just to render a static HTML file is again not correct. I don't know the correct way to tackle the issue, but if I had to serve a static HTML, then I would do something like:

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

The above example assumes that the project structure has a views directory and the static HTML files are inside it. For example, let's say, the views directory has two HTML files named index.html and about.html, then to access them, we can visit: localhost:8153/index.html or just localhost:8153/ to load the index.html page and localhost:8153/about.html to load the about.html. We can use a similar approach to serve a react/angular app by storing the artifacts in the views directory or just using the default dist/<project-name> directory and configure it in the server js as follows:

app.use(express.static('dist/<project-name>'));
夕色琉璃 2024-10-16 11:01:29

1)
最好的方法是设置静态文件夹。在你的主文件(app.js | server.js | ???)中:

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

public/css/form.html
public/css/style.css

然后你从“public”文件夹中获得静态文件:

http://YOUR_DOMAIN/form.html
http://YOUR_DOMAIN/css/style.css

2)

你可以创建你的文件缓存。
使用方法 fs.readFileSync

var cache = {};
cache["index.html"] = fs.readFileSync( __dirname + '/public/form.html');

app.get('/', function(req, res){    
    res.setHeader('Content-Type', 'text/html');
    res.send( cache["index.html"] );                                
};);

1)
The best way is to set static folder. In your main file (app.js | server.js | ???):

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

public/css/form.html
public/css/style.css

Then you got static file from "public" folder:

http://YOUR_DOMAIN/form.html
http://YOUR_DOMAIN/css/style.css

2)

You can create your file cache.
Use method fs.readFileSync

var cache = {};
cache["index.html"] = fs.readFileSync( __dirname + '/public/form.html');

app.get('/', function(req, res){    
    res.setHeader('Content-Type', 'text/html');
    res.send( cache["index.html"] );                                
};);
农村范ル 2024-10-16 11:01:29

我试图使用快速的 RESTful API 设置一个有角度的应用程序,并多次登陆此页面,尽管它没有帮助。以下是我发现有效的方法:

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)
});

I was trying to set up an angular app with an express RESTful API and landed on this page multiple times though it wasn't helpful. Here's what I found that worked:

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'));
});

Then in the callback for your api routes look like: res.jsonp(users);

Your client side framework can handle routing. Express is for serving the API.

My home route looks like this:

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)
});
ま昔日黯然 2024-10-16 11:01:29
res.sendFile(__dirname + '/public/login.html');
res.sendFile(__dirname + '/public/login.html');
倾城°AllureLove 2024-10-16 11:01:29

将以下行添加到您的代码中

  1. 将“jade”替换为“ejs”& package.json 文件中带有“*”的“XYZ”(版本)

    “依赖项”:{
       “ejs”:“*”
      }
    
  2. 然后在您的 app.js 文件中添加以下代码:

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

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

  3. 记住将所有 .HTML 文件保留在views文件夹中

干杯 :)

Add the following Lines to your code

  1. Replace "jade" with "ejs" & "X.Y.Z"(version) with "*" in package.json file

      "dependencies": {
       "ejs": "*"
      }
    
  2. Then in your app.js File Add following Code :

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

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

  3. And Remember Keep All .HTML files in views Folder

Cheers :)

烏雲後面有陽光 2024-10-16 11:01:29

这是 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}!
    `);
});

Here is a full file demo of express server!

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

hope it will help for you!

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

肩上的翅膀 2024-10-16 11:01:29

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文件放在公共文件夹中

<!DOCTYPE html>
<html>
<head>
    <title>Render index html file</title>
</head>
<body>
    <h1> I am from public/index.html </h1>
</body>
</html>

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

节点索引.js

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');
})

Put your index.html file in public folder

<!DOCTYPE html>
<html>
<head>
    <title>Render index html file</title>
</head>
<body>
    <h1> I am from public/index.html </h1>
</body>
</html>

Now run the following code in your terminal

node index.js

送你一个梦 2024-10-16 11:01:29

对于纯 html,你不需要任何 npm 包或中间件,

只需使用这个:

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

For plain html you don't require any npm package or middleware

just use this:

app.get('/', function(req, res) {
    res.sendFile('index.html');
});
最后的乘客 2024-10-16 11:01:29

我希望允许对“/”的请求由 Express 路由处理,而以前这些请求是由静态中间件处理的。这将允许我渲染 index.html 的常规版本或加载串联 + 缩小的 JS 和 CSS 的版本,具体取决于应用程序设置。受到 Andrew Homeyer 的回答的启发,我决定将我的 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');       
        });

这效果很好。

I wanted to allow requests to "/" to be handled by an Express route where previously they had been handled by the statics middleware. This would allow me to render the regular version of index.html or a version that loaded concatenated + minified JS and CSS, depending on application settings. Inspired by Andrew Homeyer's answer, I decided to drag my HTML files - unmodified - into a views folder, configure Express like so

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

And created a route handler like so

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

This worked out pretty well.

牵你手 2024-10-16 11:01:29

在 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.
});

In server.js, please include

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.
});
不醒的梦 2024-10-16 11:01:29

如果您尝试提供一个已经包含所有内容的 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 文件,上面的方法是一种非常轻量级的方法。

If you are trying to serve an HTML file which ALREADY has all it's content inside it, then it does not need to be 'rendered', it just needs to be 'served'. Rendering is when you have the server update or inject content before the page is sent to the browser, and it requires additional dependencies like ejs, as the other answers show.

If you simply want to direct the browser to a file based on their request, you should use res.sendFile() like this:

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));

This way you don't need additional dependencies besides express. If you just want to have the server send your already created html files, the above is a very lightweight way to do so.

软的没边 2024-10-16 11:01:29
  • 现在我们在 NodeJS 中使用模块。

  • 导入包

    import express from "express";
    import ejs from "ejs";
    export var app = express();
  • 设置视图引擎以使用 ejs 模板引擎来渲染带有 HTML 扩展名的文件。
    app.engine("html", ejs.renderFile);
    app.set("view engine", "html");
  • 渲染 HTML 文件:
    app.get("/", (req, res) => {
      res.render("index.html");
    });
  • Nowadays we use modules in NodeJS.

  • Import packages

    import express from "express";
    import ejs from "ejs";
    export var app = express();
  • Set up the view engine to use the ejs template engine to render files with HTML extension.
    app.engine("html", ejs.renderFile);
    app.set("view engine", "html");
  • Render the HTML file:
    app.get("/", (req, res) => {
      res.render("index.html");
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文