Nuno Miguel Silva Nuno Miguel Silva - 25 days ago 6
HTML Question

Node.js HTML page error 404 while getting javascript

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)


404 error not found

The files are all in the same directory and I don't understand why it doesn't get the scripts.

Answer

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:

var express = require('express');
var app = express();
var http = require('http').Server(app);

express.static('public')

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Now any files in the public folder will be served as you intend. (Move your *.js files to a sub-folder named public)

See the HyperDev default project template for a good interactive example of this in action.