Jason Jones
Jason Jones

Reputation: 121

HTML file can't find embedded js files

I'm currently trying to make a game using Node.js, Express, and Socket.io. However, when I attempt to run it locally I get a 404 error stating that my javascript files can't be found. My file structure looks like this:

root
| game
| | game.html
| | game.js
| index.js

And my code looks like this:

index.js

//Dependencies
var express = require('express'); //Pulls in Express framework
var http = require('http') //Pulls in http module
var socketio = require('socket.io'); //Pulls in Socket.io framework

//Instance Declarations
var app = express(); //Creates an Express instance
var server = http.createServer(app); //Creates an http server using the Express framework
var port_to_listen = process.env.PORT || 3000; //Specifies which port to listen on
var socket = socketio(http); //Creates Socket.io instance related to the server just created

//Default page displayed, always sent to index.html
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/game/game.html');
});

//Tells the server to listen for any incoming inconnections
server.listen(port_to_listen, () => {
  console.log(`listening on ${port_to_listen}`);
});

socket.on('connection', function(client) {
    console.log('Connection made')
});

//Testing to ensure socketio works
setInterval(function() {
  socket.sockets.emit('message', 'hi!');
}, 1000);

game.js

var socket = io();
socket.on('message', function(data) {
  console.log(data);
});

game.html

<html>
  <head>
    <title>A Multiplayer Game</title>
    <style>
      canvas {
        width: 800px;
        height: 600px;
        border: 5px solid black;
      }
    </style>
    <script src="/socket.io/socket.io.js"></script>
  </head>
  <body>
    <canvas id="canvas"></canvas>
  </body>
  <script type = "text/javascript" src="game.js"></script>
</html>

The error messages look like this:

error

What should I do to fix these errors?

Edit: These errors also still persist when I change the src path for game.js to

<script type = "text/javascript" src="/game/game.js"></script>

Upvotes: 0

Views: 249

Answers (1)

IvanD
IvanD

Reputation: 2943

You have only one route that serves files:

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/game/game.html');
});

The rest of the files (your css, js, etc.) are not served automatically

You need to create route(s) for that, like explained here Serving static files in Express

Upvotes: 2

Related Questions