使用express.js在node.js中提供html的最佳做法是什么? [英] What is the best practice for serving html in node.js with express.js?

查看:120
本文介绍了使用express.js在node.js中提供html的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在我的app.js / server.js文件中提供我所有的html权限:

 应用程序。 get('/',function(req,res){
res.render('index.html');
});
app.get('/ about',function(req,res){
res.render('about.html');
});
app.get('/ projects',function(req,res){
res.render('projects.html');
});

我想像如果我有15多个HTML页面,这可能不是最好的方法来调用它们。有没有更好的方法来从另一个文件或位置提供服务,并使用导出或某些东西来调用一个函数或者app.js上的东西。这可能是路由是什么,但也许我不太了解它。



(添加更多相同文件的代码)

  app.set('port',process.env.PORT || 3000); 
app.set('views',__dirname +'/ public');

//用下面的代码来渲染html文件
app.engine('html',require('ejs')。renderFile);

app.set('view engine','ejs');
app.use(express.favicon(public / img / favicon.ico));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__ dirname,'public')));


解决方案

您可以使用 static 中间件:

  app.use(/,express.static(__ dirname)); 

服务器示例:

  var express = require('express'); 
var app = express();
app.use('/',express.static(__ dirname +'/ public'));
app.listen(3000,function(){console.log('listening')});

这是文件结构:

 
├──public
│├──a.html
│├──b.html
│└──c.html
└──服务器。 js

文档:




I currently am serving all my html right in my app.js/server.js file like this:

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

I imagine if I have 15+ html pages that this is probably not the best way to call them. Is there a better way to serve them from another file or location and using export or something to be able to call just one function or something on app.js. It might be what the routing is for but maybe I do not understand it too well.

(added more code that is in the same file)

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/public');

// used below code to render html files
app.engine('html', require('ejs').renderFile);

app.set('view engine', 'ejs');
app.use(express.favicon("public/img/favicon.ico"));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

解决方案

You could use the static middleware:

app.use("/", express.static(__dirname));

A server example:

var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/public'));
app.listen(3000, function() { console.log('listening')});

This is the file structure:

.
├── public
│   ├── a.html
│   ├── b.html
│   └── c.html
└── server.js

Documentation:

这篇关于使用express.js在node.js中提供html的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆