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
     --javascripts 
          client.js
  -- views
       index.jade
       layout.jade

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

the layout.jade file contains:

!!! 5
html(lang="en")
    head
        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")
    body 
        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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top