Im working with node.js and I wanted my HTML file to GET javascript files.
This is the file i'm running with node.js called server.js
:
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Very simple code made to host index.html
. This HTML file has some script tags:
<script type="text/javascript" src="./A.js"></script>
<script type="text/javascript" src="./B.js"></script>
<script type="text/javascript" src="./C.js"></script>
And the problem is that when i run server.js
and I go to the browser I get this errors on the console:
GET http://localhost:3000/A.js
GET http://localhost:3000/B.js
GET http://localhost:3000/C.js 404 (Not Found)
The files are all in the same directory and I don't understand why it doesn't get the scripts.
Try looking at the Express1 Documentation for serving static files.
You're serving your index file with these lines:
You can serve js files the same way or by putting them in a
public
folder and addingapp.use(express.static('public'))
.Then you can reference them as
public/A.js
Your
server.js
does not know how to handle anything besides requests for the root page. (Even http://localhost:3000/index.html will fail with a 404.)Add the
express.static
middleware to serve files from a directory:Now any files in the
public
folder will be served as you intend. (Move your *.js files to a sub-folder namedpublic
)See the HyperDev default project template for a good interactive example of this in action.