I am having trouble setting up the middle-ware of my application so that it serves some of my static files such as css and js. I would like to be able to include my css and js files that are inside of the public directory in my index.html .
This is a picture of my current file structure.
This is the code for my express server.
server.js
var express = require('express');
var path = require('path');
var app = express();
//config
app.set('views', __dirname + '');
app.engine('html', require('ejs').renderFile);
//app.use(express.static(__dirname + '/')); worked when everything was in jqtest
app.use(express.static(__dirname + '/public'));
//routes
app.get('',function(req,res){
res.render('../public/views/index.html')
});
app.env
//server
app.listen(process.env.PORT || 5000);
console.log('app live in 5000');
These are the src tags I am trying to use in my index.html ,but are not working. I know I will probably need to set up an additional app.use for the jquery file located in components as well.
index.html
<link rel="stylesheet" type="text/css" href="/public/css/style.css"/>
<script type="text/javascript" src="/components/jQuery/dist/jquery.js"></script>
<script type="text/javascript" src="/public/js/myJS.js"></script>
Edit 1 I have made my github for this proj public. It is available Here
Edit 2
This has been answered. Thank you very much to teleaziz and 7zark7 for helping guide me through this process.
Solution:
Step 1:
So the problem when removing your application server code outside of the root director is that __dirname is not a global variable. The first step to setting up the routes for my static files was to tell my server when the new root is. I did this by adding this line of code provided by teleaziz
var root = path.normalize(__dirname + '/..');
Step 2:
Once I did that I had to change the route for public to use root instead of __dir as advised by teleaziz
app.use(express.static(root + '/public'));
Step 3:
Once that was completed I removed /public/ from the src in my index.html as advised by teleaziz and 7zark7. My new src tags that work look like this.
<link rel="stylesheet" type="text/css" href="/css/style.css"/>
<script type="text/javascript" src="/components/jQuery/dist/jquery.js"></script>
<script type="text/javascript" src="/js/myJS.js"></script>