Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node rendered HTML file not finding relative path Scripts

Tags:

node.js

New to node, and have it running pulling in an HTML page using Express and EJS

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

//load up index file
app.get('/', function(req, res){
    res.render('index.html');
});

However the HTML includes some relative path JS scripts

 <html>
  ....more...
 <script src="js/libs/jquery.js"></script>
 <script src="js/libs/underscore.js"></script>
 <script src="js/libs/backbone.js"></script>

If i run my HTML page via my original "localhost/myProject" it all works fine. However if i launch my file via Node which is set to "localhost:8080"

 app.server.listen(8080);

Then it no longer finds the "/js" directory. Is there some sort of configuration that I am missing, or should i go about this another way?

Update: Just found this

app.use(express.static( __dirname + '/public' ));

might be what I am looking for, although i need to do some refactoring

like image 683
abritez Avatar asked May 08 '13 04:05

abritez


1 Answers

you should configure express to server static files, for example, put all the static files under a directory called 'public'

app.configure(function () {
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use('/public', express.static(__dirname + '/public'));
    app.use(app.router);    
});

then in your html:

    <script src="/public/js/libs/jquery.js"></script>
like image 76
ltebean Avatar answered Oct 31 '22 13:10

ltebean