【问题标题】:Loading static files like CSS and JS to ejs将 CSS 和 JS 等静态文件加载到 ejs
【发布时间】:2017-11-06 12:19:43
【问题描述】:

我正在尝试将一些静态文件加载到 ejs(我能够加载 HTML 文件,但不能加载到 ejs 文件中)。不仅仅是静态文件。 我什至无法加载 CDN 文件!有人可以帮我了解我哪里出错了吗? 这是目录结构:

这是我的 server.js:

const express=require('express');
var app=express();
const MongoClient = require('mongodb').MongoClient
app.set('view engine', 'ejs')
var path = require('path')
app.use('/static',express.static(__dirname + '/public'));

app.get('/',function(req,res){
 db.collection('testCollection').find().toArray((err, result) => {
    if (err) return console.log(err)
    console.log(result)
    res.render('index.ejs', {testCollection: result})
  })
});

这是我的 index.ejs:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/main.css"/>
</head>
<body>
<form>
<div id="container"></div>
<ul class="quotes">
 <% for(var i=0; i<testCollection.length; i++) {%>
    <li class="quote">
      <span><%= testCollection[i].name %></span>
    </li>
  <% } %>
</ul>
</form>
</body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="/static/main.js"></script>
</html>

在控制台中我只能看到加载的 index.ejs 文件:

【问题讨论】:

    标签: javascript html node.js express ejs


    【解决方案1】:

    我认为如果你添加:

    app.set('views',__dirname);//---> before setting ejs as the View Engine ... (this is for the views folder that you have there but your view is in your current working directory hence __dirname)
    var index = require('./index');
    app.use('/', index);//---> after declaring static folder...
    

    到你的代码节点可能知道文件在哪里...


    我建议你将index.ejs移动到views文件夹,然后设置:

    app.set('views', path.join(__dirname, 'views'));
    

    代替:

    app.set('views',__dirname);
    

    【讨论】:

      【解决方案2】:

      &lt;link rel="stylesheet" href="/main.css"/&gt;

      &lt;script src="/main.js"&gt;&lt;/script&gt;

      以上是您应该如何调用 index.ejs 中的文件。您将这样做是因为您在 server.js 文件中声明 app.use('/static',express.static(__dirname + '/public'));

      【讨论】:

      • &lt;link&gt; 标签没有右斜线。
      猜你喜欢
      • 2015-12-27
      • 2016-08-09
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多