1

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: 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>

In the console I can see only index.ejs file loaded:Console

2 Answers 2

4

<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'));

Sign up to request clarification or add additional context in comments.

1 Comment

The <link> tag has no closing slash.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.