Javascript 呈现基本HTML视图?
我有一个基本的node.js应用程序,我正在尝试使用Express framework启动它。我有一个Javascript 呈现基本HTML视图?,javascript,html,node.js,mongodb,express,Javascript,Html,Node.js,Mongodb,Express,我有一个基本的node.js应用程序,我正在尝试使用Express framework启动它。我有一个views文件夹,其中有一个index.html文件。但是我在加载web浏览器时收到以下错误 错误:找不到模块“html” 下面是我的代码 var express = require('express'); var app = express.createServer(); app.use(express.staticProvider(__dirname + '/public')); app
views
文件夹,其中有一个index.html
文件。但是我在加载web浏览器时收到以下错误
错误:找不到模块“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')
我在这里遗漏了什么?来自Express.js指南: 查看文件名的格式为
Express.ENGINE
,其中ENGINE
是所需模块的名称例如,视图layout.ejs
将告诉视图系统require('ejs')
,加载的模块必须导出方法exports.render(str,options)
以符合Express,但是app.register()
可用于将引擎映射到文件扩展名,例如,jade可以呈现foo.html
因此,要么创建自己的简单渲染器,要么使用jade:
app.register('.html', require('jade'));
关于app.register
请注意,在Express 3中,此方法被重命名
您还可以读取HTML文件并发送:
app.get('/', (req, res) => {
fs.readFile(__dirname + '/public/index.html', 'utf8', (err, text) => {
res.send(text);
});
});
试试这个。它对我有用
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");
});
您可以让jade包含一个普通HTML页面: 在视图/index.jade中
include plain.html
在views/plain.html中
<!DOCTYPE html>
...
对于我的项目,我创建了以下结构:
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);
我在
express3.X
和node 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)
注意:您必须安装ejs
模板引擎
npm install -g ejs
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");
})
例如:
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。这些答案中有许多已经过时。 使用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');
});
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}`);
});
这假设您的视图位于视图
子文件夹中,并且您已经安装了ejs
节点模块。如果不是,请在节点控制台上运行以下操作:
npm install ejs --save
如果您不必使用视图目录,只需将html文件移动到下面的公共目录即可 然后,将此行添加到app.configure中,而不是“/views” server.use(express.static(__dirname + '/public')); 使用(express.static(uu dirname+'/public'); 如果您使用的是express@~3.0.0,请从示例中更改以下行:
app.use(express.staticProvider(__dirname + '/public'));
对这样的事情:
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
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)
});
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));
我按照上面的描述制作,效果很好。通过这种设置,您不必编写额外的代码,这样就可以轻松地用于微生产或测试
完整代码如下:
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')
我通常用这个
app.configure(function() {
app.use(express.static(__dirname + '/web'));
});
只是要小心,因为这会共享/web目录中的任何内容
我希望这能有所帮助
(一)
最好的方法是设置静态文件夹。在主文件(app.js | server.js |?)中:
public/css/form.htmlpublic/css/style.css 然后从“公共”文件夹中获取静态文件:
(二) 您可以创建文件缓存。
使用方法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"] );
};);
我试图用一个快速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(用户)代码>
您的客户端框架可以处理路由。Express是为API服务的
我的回家路线如下所示:
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
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)
});
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 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我希望允许“/”请求通过快速路由处理,而以前它们是由statics中间件处理的。这将允许我根据应用程序设置呈现index.html的常规版本,或者加载连接+缩小JS和CSS的版本。受此启发,我决定将我的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');
});
这很有效。我在下面添加了2行,它对我很有效
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
在Express routes中尝试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");
阅读此处:在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.
});
在代码中添加以下行
将package.json文件中的“jade”替换为“ejs”和“X.Y.Z”(版本)替换为“*”
"dependencies": {
"ejs": "*"
}
然后在app.js文件中添加以下代码:
app.engine('html',require('ejs').renderFile)代码>
app.set('view engine','html')代码>
并记住将所有.HTML文件保存在“视图”文件夹中
干杯:)我不想依靠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 );
} );
要在节点中呈现Html页面,请尝试以下操作:
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
- 您需要通过
npm
安装ejs
模块,如:
npm install ejs --save
这里是express server的完整文件演示强>
希望对你有帮助
//用于HTML页面的simple express服务器!
//ES6风格
const express=require('express');
常数fs=要求('fs');
常量主机名='127.0.0.1';
常数端口=3000;
常量app=express();
让缓存=[];//阵列正常!
cache[0]=fs.readFileSync(uu dirname+'/index.html');
cache[1]=fs.readFileSync(uu dirname+'/views/testview.html');
应用程序获取(“/”,(请求,请求)=>{
res.setHeader('Content-Type','text/html');
res.send(
.
├── index.html
├── node_modules
│ ├──{...}
└── 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')
<!DOCTYPE html>
<html>
<body>
<div> hello world </div>
</body>
</html>
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));
app.get('/', function(req, res) {
res.sendFile('index.html');
});
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');
})
<!DOCTYPE html>
<html>
<head>
<title>Render index html file</title>
</head>
<body>
<h1> I am from public/index.html </h1>
</body>
</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}`);
});
app.use(express.static('dist/<project-name>'));
.
├── node_modules
│
├── views
│ ├──index.html
└── app.js
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");
})
res.sendFile(path.join(__dirname, 'htmlfiles\\index.html'))