I am trying to load some static files to ejs (I was able to load in HTML file but not here in ejs file). Not just static files. I am not even able to load the CDN files! Can someone please help me to understand where I am going wrong? Here is the directory structure:
This is my 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}) }) });
This is my 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>
<link rel="stylesheet" href="/main.css"/>
<script src="/main.js"></script>
Above is how you should call your files in index.ejs. You are going to do so because you declare in your server.js
file app.use('/static',express.static(__dirname + '/public'));
I think that if you add :
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...
to your code node might know where the files are ...
I suggest that you move your index.ejs
to the views folder and then set:
app.set('views', path.join(__dirname, 'views'));
instead of:
app.set('views',__dirname);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.