I'm creating an app that has separate server and client code (two different git repositories).
The HTML is there just as a UI, but it still needs to load /socket/socket.io.js
in order to communicate with the server.
This is my HTML:
<html>
<head>
<script src="/socket/socket.io.js"></script>
<script src="js/myStuff.js"></script>
</head>
<body>
</body>
</html>
When queried with an address that starts with /c
, the server will automatically replace the prefix with the client code directory. So, the website is loaded like this: localhost:8080/c/index.html
, and the request for js/myStuff.js
is actually /c/js/myStuff.js
.
This is how it's all implemented:
var http = require("http");
var io = require("socket.io");
var fs = require("fs");
var iniparser = require("iniparser");
var config = iniparser.parseSync('./config.ini');
clientPath = config.server.clientPath; // ../../Bla
var handler = function(req, res)
{
if (req.url[1] == "c")
{
req.url = req.url.slice(2, req.url.length); //Cut off the "/c"
url = __dirname + "/" + clientPath + req.url;
}
else
{
url = req.url; //Nothing.
}
fs.readFile (url, function(err, data)
{
if (err)
{
res.writeHead(404);
return res.end("File not found.");
}
res.writeHead(200);
res.end(data);
});
}
var server = http.createServer(handler);
server.listen(8080);
var socket = io.listen(server);
Both myStuff.js and index.html load correctly, but there is a problem with loading /socket/socket.io.js
. That is very, very strange, because I don't even touch the address.
This error is given by Google Chrome:
GET http://localhost:8080/socket/socket.io.js 404 (Not Found)
Why is this happening and how can I fix it?
It doesn't look as if you are changing it anywhere so the default location for the Socket.io JavaScript is
<script src="/socket.io/socket.io.js"></script>
not socket/socket.io.js.