Home » Nodejs » Why can't I get to my javascript files from Expressjs/Nodejs?

Why can't I get to my javascript files from Expressjs/Nodejs?

Posted by: admin November 29, 2017 Leave a comment


I’m starting to experiment with nodejs/expressjs/coffeescript and the jade view engine.

I have the following setup which from what I can see from the examples that are around seems pretty standard.

    app = express.createServer().listen process.env.PORT

    app.configure ->
        app.set 'views', __dirname + '/views'
        app.set 'view engine', 'jade'
        app.set 'view options', layout: true
        app.use express.bodyParser()
        app.use express.static(__dirname + '/public')
        app.use app.router

    app.get '/ekmHoliCal/index', (req, res) ->
        res.render 'index'

My directory structure is as follows:

-- ekmHoliCal
  -- public
  -- views

The index file contains nothing but the the line:
This is the index file

the layout.jade file contains:

!!! 5
        title Users
        script(type="text/javascript", src="http://code.jquery.com/jquery-1.6.4.js")
        script(type="text/javascript", src="/ekmholical/javascripts/client.js")
        div!= body 

When I navigate to localhost/ekmHoliCal/index I get served the index page as expected. However if I view source I see a link to to jquery :

<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.js">

and if I click on that link sure enough I see the source of the jquery file.

The index file source also contains a link to my client.js file as follows:

<script type="text/javascript" src="/ekmholical/javascripts/simon.js"></script>

but when I click on that I get

Cannot GET /ekmholical/javascripts/client.js

I’ve seen this related question (Express-js can't GET my static files, why?) and can’t see what I’m doing wrong


Your script tag has the wrong path. it should be

<script type="text/javascript" src="/javascripts/simon.js"></script>

In express, you’ve set the following:

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

That tells express/node that the public directory should act as your web root. Everything in it can be referenced via /, so if you also have a CSS folder in there, you might use /css/styles.css


Following up on what Paul Armstrong said, you could also do this.

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

This will allow you to reference your js file like this:

<script src="/public/javascripts/simon.js"></script>