简体   繁体   English

如何使用ExpressJS(在主目录/根目录视图上)使用参数呈现HTML视图?

[英]How to render HTML view with parameters using ExpressJS (on the home/root view)?

I'd like send a parameter and render a html file when the user go to the home page of my app. 当用户转到我的应用首页时,我想发送一个参数并呈现一个html文件。

Here is what I did so far: 这是我到目前为止所做的:

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
    console.log('Hi !'); // never displayed
    res.render('index', { foobar: 'foobar'});
});

The HTML is properly rendered (probably due to express.static ) but app.get('/') seems to be never called so I can't return the variable. HTML已正确呈现(可能是由于express.static引起的),但是app.get('/')似乎从未被调用过,所以我无法返回变量。

How can I return a variable from a call to '/' with the static HTML page public/index.html ? 如何通过静态HTML页面public / index.html调用'/'返回变量?

My ultimate goal is to be able to use foobar in my JS without any additional call to the server. 我的最终目标是能够在我的JS中使用foobar ,而无需对服务器进行任何其他调用。 Could you help me to achieve this? 你能帮我实现这个目标吗?

var express = require('express');
var router = express.Router();

router.get('/index',function(req,res){
    res.sendFile(path.resolve('./public/index.html'));

});



module.exports = router;

If you have a file named index.html in your public/ directory, express.static() will return that file if the url / is requested, so your route handler will never get passed the request. 如果您的public/目录中有一个名为index.html文件,则如果请求url / ,则express.static()将返回该文件,因此您的路由处理程序将永远不会传递请求。

Generally, templates are stored in a separate directory than static (public) resources. 通常,模板存储在与静态(公共)资源不同的目录中。 Express, by default, will look for templates in the ./views directory (unless you tell it otherwise) so if you move your index.html to there it will get rendered by EJS (but see below), and you can use your parameters in it. Express默认情况下会在./views目录中查找模板(除非另行说明),因此,如果将index.html移到该目录,它将由EJS呈现(但请参见下文),并且可以使用参数在里面。

Since EJS will by default look for files ending with a .ejs extension, if you want to keep on using .html , you need to set up Express as follows: 由于EJS默认情况下将查找以.ejs扩展名结尾的文件, .ejs ,如果要继续使用.html ,则需要按以下方式设置Express:

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

This tells Express to look for files with extension .html in the ./views directory, and to render those files using EJS. 这告诉Express在./views目录中查找扩展名为.html的文件,并使用EJS呈现这些文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM