Javascript 渲染原始 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14115893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Render raw HTML
提问by Randomblue
I want to render raw .htmlpages using Express 3 as follows:
我想.html使用 Express 3渲染原始页面,如下所示:
server.get('/', function(req, res) {
res.render('login.html');
}
This is how I have configured the server to render raw HTML pages (inspired from this outdated question):
这就是我配置服务器以呈现原始 HTML 页面的方式(灵感来自这个过时的问题):
server
.set('view options', {layout: false})
.set('views', './../')
.engine('html', function(str, options) {
return function(locals) {
return str;
};
});
Unfortunately, with this configuration the page hangs and is never rendered properly. What have I done wrong? How can I render raw HTLM using Express 3 without fancy rendering engines such as Jade and EJS?
不幸的是,使用这种配置页面会挂起并且永远不会正确呈现。我做错了什么?如何在没有 Jade 和 EJS 等花哨渲染引擎的情况下使用 Express 3 渲染原始 HTLM?
采纳答案by hunterloftis
If you don't actually need to inject data into templates, the simplest solution in express is to use the static file server (express.static()).
如果您实际上不需要将数据注入到模板中,express 中最简单的解决方案是使用静态文件服务器 ( express.static())。
However, if you still want to wire up the routes to the pages manually (eg your example mapping '/' to 'login.html'), you might try res.sendFile()to send your html docs over:
但是,如果您仍然想手动将路由连接到页面(例如,将“/”映射到“login.html”的示例),您可以尝试res.sendFile()将您的 html 文档发送到:
回答by shash7
What I think you are trying to say is: How can I serve static html files, right?
我认为您想说的是:我如何提供静态 html 文件,对吗?
Let's get down to it.
让我们开始吧。
First, some code from my own project:
首先,我自己项目中的一些代码:
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
What this means that there is a folder named public inside my app folder. All my static content such as css, js and even html pages lie here.
这意味着我的应用程序文件夹中有一个名为 public 的文件夹。我所有的静态内容,如 css、js 甚至 html 页面都在这里。
To actually send static html pages, just add this in your app file
要实际发送静态 html 页面,只需将其添加到您的应用程序文件中
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/layout.html');
});
So if you have a domain called xyz.com; whenever someone goes there, they will be served layout.html in their browsers.
因此,如果您有一个名为 xyz.com 的域;无论何时有人去那里,他们都会在浏览器中看到 layout.html。
Edit
编辑
If you are using express 4, things are a bit different. The routes and middleware are executed exactly in the same order they are placed.
如果您使用 express 4,情况会有所不同。路由和中间件的执行顺序与它们放置的顺序完全相同。
One good technique is the place the static file serving code right after all the standard routes. Like this :
一种很好的技术是将静态文件服务代码放在所有标准路由之后。像这样 :
// All standard routes are above here
app.post('/posts', handler.POST.getPosts);
// Serve static files
app.use(express.static('./public'));
This is very important as it potentially removes a bottleneck in your code. Take a look at this stackoverflow answer(the first one where he talks about optimization)
这非常重要,因为它可能会消除代码中的瓶颈。看看这个stackoverflow 答案(第一个他谈论优化的地方)
The other major change for express 4.0 is that you don't need to use app.configure()
express 4.0 的另一个主要变化是你不需要使用 app.configure()
回答by sheldonk
Have you tried using the fs module?
您是否尝试过使用 fs 模块?
server.get('/', function(req, res) {
fs.readFile('index.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}
回答by tztxf
as the document says : 'Express expects: (path, options, callback)' format function in app.engin(...).
正如文档所说:'Express 期望:(路径,选项,回调)' app.engine(...) 中的格式函数。
so you can write your code like below(for simplicity, but it work):
所以你可以像下面这样编写代码(为了简单起见,但它可以工作):
server
.set('view options', {layout: false})
.set('views', './../')
.engine('html', function(path, options, cb) {
fs.readFile(path, 'utf-8', cb);
});
of course just like 2# & 3# said, you should use express.static() for static file transfer; and the code above not suit for production
当然就像 2# & 3# 说的,你应该使用 express.static() 进行静态文件传输;并且上面的代码不适合生产
回答by Jay Kumar
First, the mistake you did was trying to use the express 2.x code snippet to render raw HTML in express 3.0. Beginning express 3.0, just the filepath will be passed to view engine instead of file content.
首先,您犯的错误是尝试使用 express 2.x 代码片段在 express 3.0 中呈现原始 HTML。从 express 3.0 开始,只会将文件路径而不是文件内容传递给视图引擎。
Coming to solution,
来到解决方案,
create a simple view engine
创建一个简单的视图引擎
var fs = require('fs');
function rawHtmlViewEngine(filename, options, callback) {
fs.readFile(filename, 'utf8', function(err, str){
if(err) return callback(err);
/*
* if required, you could write your own
* custom view file processing logic here
*/
callback(null, str);
});
}
use it like this
像这样使用它
server.engine('html', rawHtmlViewEngine)
server.set('views', './folder');
server.set('view engine', 'html');
Reference
参考
Official express 2.x to 3.x migration guide
官方 express 2.x 到 3.x 迁移指南
See 'Template engine integration' section in this url https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
请参阅此网址中的“模板引擎集成”部分 https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
回答by FredTheWebGuy
After a fresh install of the latest version of Express
全新安装最新版本的 Express 后
express the_app_name
Creates a skeleton directory that includes app.js.
创建一个包含app.js的骨架目录。
There is a line in app.jsthat reads:
app.js中有一行是这样写的:
app.use(express.static(path.join(__dirname, 'public')));
So a folder named publicis where the magic happens...
所以一个名为public的文件夹是神奇发生的地方......
Routing is then done by a function modeled this way:
然后通过以这种方式建模的函数完成路由:
app.get('/', function(req,res) {
res.sendfile('public/name_of_static_file.extension');
});
*Example:*An index.htmlinside the public folder is served when invoked by the line:
*实施例:*一个index.html的公共文件夹内时由线调用供应:
app.get('/', function(req,res) {
res.sendfile('public/index.html');
});
As far as assets go: Make sure the css and javascript files are called from the folder relative to the publicfolder.
就资产而言:确保从相对于公共文件夹的文件夹调用 css 和 javascript 文件。
A vanilla Express install will have stylesheets, javascripts, and imagesfor starting folders. So make sure the scripts and css sheets have the correct paths in index.html:
vanilla Express 安装将包含样式表、javascripts和用于启动文件夹的图像。因此,请确保脚本和 css 表在index.html 中具有正确的路径:
Examples:
例子:
<link href="stylesheets/bootstrap.css" rel="stylesheet">
or
或者
<script src="javascripts/jquery.js"></script>
回答by Meet Mehta
You can render .html pages in express using following code:-
您可以使用以下代码在 express 中呈现 .html 页面:-
var app = express();
app.engine('html', ejs.__express);
And while rendering, you can use following code:-
在渲染时,您可以使用以下代码:-
response.render('templates.html',{title:"my home page"});
回答by stone
I wanted to do this because I'm creating a boilerplate NodeJS server that I don't want tied to a view engine. For this purpose it's useful to have a placeholder rendering engine which simply returns the (html) file content.
我想这样做是因为我正在创建一个样板 NodeJS 服务器,我不想将它绑定到视图引擎。为此,拥有一个仅返回 (html) 文件内容的占位符渲染引擎非常有用。
Here's what I came up with:
这是我想出的:
//htmlrenderer.js
'use strict';
var fs = require('fs'); // for reading files from the file system
exports.renderHtml = function (filePath, options, callback) { // define the template engine
fs.readFile(filePath, function (err, content) {
if (err) return callback(new Error(err));
var rendered = content.toString();
// Do any processing here...
return callback(null, rendered);
});
};
To use it:
要使用它:
app.engine('html', htmlRenderer.renderHtml);
app.set('view engine', 'html');
Source: http://expressjs.com/en/advanced/developing-template-engines.html
来源:http: //expressjs.com/en/advanced/developing-template-engines.html
Comments and constructive feedback are welcome!
欢迎提出意见和建设性反馈!
回答by efkan
After years a new answer is here.
多年后,一个新的答案就在这里。
Actually this approach like skypecakess answer;
实际上这种方法就像skypecakess 的答案;
var fs = require('fs');
app.get('/', function(req, res, next) {
var html = fs.readFileSync('./html/login.html', 'utf8')
res.send(html)
})
That's all...
就这样...
Also if EJS or Jade will be used the below code could be used:
此外,如果将使用 EJS 或 Jade,则可以使用以下代码:
var fs = require('fs');
app.get('/', function(req, res, next) {
var html = fs.readFileSync('./html/login.html', 'utf8')
res.render('login', { html: html })
})
And views/login.ejsfile contains only the following code:
并且views/login.ejs文件仅包含以下代码:
<%- locals.html %>
回答by Robert
app.get('/', function(req, res) {
returnHtml(res, 'index');
});
function returnHtml(res, name) {
res.sendFile(__dirname + '/' + name + '.html');
}
And put your index.html to your root page, of course you could create a /views folder for example and extend returnHtml() function.
并将你的 index.html 放到你的根页面,当然你可以创建一个 /views 文件夹并扩展 returnHtml() 函数。

