简体   繁体   English

如何使用 express 和 ejs 提供静态文件并发送数据?

[英]How to serve static files using both express and ejs and send the data?

I am trying to serve files with express and send data to an html file using ejs.我正在尝试使用 express 提供文件并使用 ejs 将数据发送到 html 文件。 The problem is that I only have to use either express to serve the files or ejs to send data but for some reason I cant use both.问题是我只需要使用 express 来提供文件或使用 ejs 来发送数据,但由于某种原因我不能同时使用两者。 My paths are right but probably I have to do something different to make both work.我的路径是正确的,但可能我必须做一些不同的事情才能使两者都有效。 My code doesnt reach app.get when I use app.use(express.static('../dist')) , but when I comment that line it does send the data.当我使用app.use(express.static('../dist')) ,我的代码没有到达 app.get ,但是当我注释该行时,它确实发送了数据。 If I can know what is happening that would be great.如果我能知道发生了什么,那就太好了。

My code is the following:我的代码如下:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

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

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

app.listen(4000, function() { console.log('listening')});

let views;

jwt.authorize((err, response) => {
    google.analytics('v3').data.ga.get(
        {
            auth: jwt,
            ids: 'ga:' + view_id,
            'start-date': '30daysAgo',
            'end-date': 'today',
            metrics: 'ga:sessions, ga:pageviews'
        },
        (err, result) => {
            console.log();
            views = result;
            console.log(views.data.rows[0][0]);

            app.get('/', function(req, res){
                console.log('test');
                res.render('../dist/index.html',{sessions:views.data.rows[0][0], pageviews:views.data.rows[0][1]});
            });
        }
    );
});

If two routes match one URL, then whichever route is defined first will be used.如果两个路由匹配一个 URL,则将使用第一个定义的路由。

/ hits the static route, finds a match (with an index.html file) and serves it up. /命中静态路由,找到匹配项(使用index.html文件)并提供它。

The route matching code never gets as far as app.get('/' .路由匹配代码永远不会达到app.get('/'


EJS files are not static files. EJS 文件不是静态文件。 Don't mix them together with your static files.不要将它们与静态文件混合在一起。

If there isn't an index.html in the directory you keep your static files in, then it won't match on the static route, so the route matching code will reach app.get('/' .如果您保存静态文件的目录中没有index.html ,则它不会在静态路由上匹配,因此路由匹配代码将到达app.get('/'

You should probably separate the files (into static and templates rather then lumping them together in dist ) and make it clear which files are EJS templates by giving them .ejs file extensions instead of .html .您可能应该将文件分开(分为statictemplates而不是将它们放在dist ),并通过给它们提供.ejs文件扩展名而不是.html来明确哪些文件是 EJS 模板。

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

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