Reputation: 2027
This is driving me insane.
I have a node app with express. It serves up a file called index.ejs.
All I wanna do is import a javascript file on this page (something like jquery). But it won't pull it up, and I'm going nuts (as this should be simple).
On the server side I have this code in a file called app.js:
var express = require('express');
var app = express.createServer();
var hostName = (process.env.VCAP_APP_HOST || 'localhost');
app.listen( process.env.VCAP_APP_PORT || 8000);
app.use(express.static(__dirname + '/public/javascript/'));
//Create the view
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', { layout: false });
app.get('/', function(req, res){
res.render('index.ejs', {
item : "document.write('Hello World');"
});
});
In the ejs file, I have this:
<html>
<script>
<%= item %>
</script>
<a href="">Link</a>
<script type="text/javascript" src="/javascript/jquery.js"></script>
</html>
I can see in the console that the script is not loaded (it shows an error). But for the life of me I can't figure out why.
Upvotes: 1
Views: 5369
Reputation: 15003
When your client asks for /javascript/jquery.js
, your server is going to be looking for /public/javascript/javascript/jquery.js
, and I rather doubt it will find it. Setting express.static()
's pathname to __dirname + '/public'
should work, assuming that jquery.js
is actually located in your_app/public/javascript
.
Upvotes: 0
Reputation: 9055
You need to add a static server to serve the other files you have under '/'. Currently your server is just responding to requests sent to '/' (and views).
Add this line to your express setup before app.get
:
// DOCUMENT_ROOT should point to the directory that contains your javascript directory.
app.use(express.static(DOCUMENT_ROOT));
Upvotes: 3