6

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

1
  • Try referencing with /js... not just js... Commented May 8, 2013 at 6:37

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I just ran into the static file config. Thanks. Will mark correct once the system allows me to.
Note that express configure method has been depreciated and doesn't work with 4.X.X

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.