简体   繁体   中英

Express.io does not load Javascript file

I have a Express.io server running, which works fine, however my Javascript files will not load properly.

I have a Jade file, which looks like this:

html
    head
        h1 Test index
    body
        script(src="/socket.io/socket.io.js")
        script(src="/javascripts/inHTML.js")

and a Coffescript file which looks like this:

express = require('express.io')
app = express()
r   = require('rethinkdb')

app.get '/', (req, res) ->
    res.render '../../client.jade'

The Jade file does load and script(src="/socket.io/socket.io.js") loads properly as well, however the second <script> tag returns an GET error when I am inspecting the site with Chrome. I have tried multiple paths to make it work, unfortunately without success. I do not see any reason why script(src="/socket.io/socket.io.js") does load, while my other script does not.

My project looks like this: website is the main directory, which contains

  • coffeescripts (folder)
  • javascripts (folder - has app.js and inHTML.js)
  • data (folder)
  • node_modules (folder - has /socket.io/socket.io.js)
  • Package.json (file)
  • client.jade (file)

When I console.log __dirname is prints website/javascripts

I also tried app.use express.static('../' + __dirname) or anything similar, also no success.

EDIT: I tried to do the Express.io Routing Example , however I want the Javascript in a seperate .js file.

If i am understanding you correctly you have the javascript inHTML.js in the same directory as your executing script app.js. __dirname is the name of the directory that the currently executing script resides in. That is why the console logs website/javascripts when you log __dirname .

So basically, that would mean you would write app.use(express.static(__dirname + '/')) and script(src="inHTML.js") . Or maybe you could write app.use(express.static('../')); and script(src="javascripts/inHTML.js")

The most logical thing to do, and what I would suggest, is on the other hand placing your executing script, again I am assuming that is app.js, in the root directory and placing all the files you want to serve as static in the same subfolder. That way you can state that app.use(express.static(__dirname + '/nameOfSubfolder')); . and the path to your static files will be more logical since they all have the same starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM