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:
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>
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
Related
I'm using a Node.js server to show an HTML file. The HTML uses a Javascript file to get some info but I'm not being able to access that file. Here's my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Swarm Profile</title>
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
And my Node.js server file:
var http = require('http');
var fs = require('fs');
const hostname = '127.0.0.1';
const port = 9000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.createReadStream("./index.html").pipe(res);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What should I use to be able to access the script.js file?
There are many static file handler modules already in node, take a look at:
Node static modules
Most popular are: Node-Paperboy and Node-Static
Using node static is as simple as:
var static = require('node-static');
var file = new(static.Server)('./public');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
file.serve(request, response);
});
}).listen(8080);
I'm writing a simple server with expressjs:
'use strict';
var express = require('express');
var logger = require('morgan');
var path = require('path');
var bodyParser = require('body-parser');
var api = require('./routes/main');
var app = express();
app.disable('x-powered-by');
app.use(logger('dev')); //Used to log HTTP requests
app.use(bodyParser.urlencoded({ extended: true })); //Used to automatically parse requests body
app.use(bodyParser.json());
app.use('/api', api);
app.use('/*', express.static('./public')); //serving static files under public folder
app.use(function(req,res){
res.send("404");
});
var server = app.listen(8000, "0.0.0.0", function () {
console.log('RAVE listening on port ' + server.address().port + 'hosting at ' + server.address().address);
});
module.exports = app;
in public directory there are index.htm, some css files and one js script, When index.html tries to load css or js scripts, it does through GET /path/file.css/ and loads a directory instead of file.css. Why??
index.html:
<head>
....
<link rel="stylesheet" href="/stylesheets/view-style.css" type="text/css" />
<script type="text/javascript" src="/js/main.js"></script>
</head>
console:
GET /stylesheets/view-style.css/ 200 8.979 ms - 10602
GET /js/main.js/ 200 8.598 ms - 10602
chrome sources:
I know you have already solved the problem . But just for future reference .
We have something called cache-busting . Basically use
<script type="text/javascript" src="/js/main.js?version=1"></script>
Whenever you change the file change the version number in the code above
so as said above, i run the html file only and i'm able to see the pictures, but when i run the file via node it sends me a 404 error on the file i used.
<html>
<body>
<img src="aaa.jpg" />
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
</script>
</body>
</html>
and the node code
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
how can i stop this from happening?
To serve static files such as images and scripts, you need to include a middleware that serves static files. Put all your static files inside of a public directory and serve them like this.
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
// Serve static files
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
I am trying to develop a chat application using Express js(jade template ) and socket.io.Here is my app.js
var express = require('express');
var path = require('path');
var http = require('http');
var io = require('socket.io')(http);
var app = express();
//start chat with socket io
io.sockets.on('connection',function(socket){
console.log("connection");
socket.on('send message',function(data,callback){
var msg=data.trim();
if(msg==null){
callback("enter a messsage");
}else{
console.log("chat message"+msg);
io.sockets.emit('new message',{msg:msg});
}
});
});
//end socket
Here is my chat.js file on client side
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
var $message=$('#message');
var $messageForm=$('#send-message');
//opens a connection and send to sever
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message',$message.val(),function(data){
console.log("data"+data);
});
$message.val('');
});
//read the chat messages from users
socket.on('new message',function(data){
console.log('data.msg');
});
});
chat.jade file
<form id="send-message">
<input type="text" id="message">
<input type="submit" value="submit"/>
</form>
<script src="http://localhost/api/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
I will get 404 error on this file http://localhost:3000/socket.io/socket.io.js. Also get a Uncaught ReferenceError: io is not defined in chat.js script.I think this is because of missing socket.io.js file.
You have a couple of issues.
Serving static files in your jade templates you should be using something like this:
link(rel='text/javascript', href='/js/socket.io.js')
These files will normally be contained within a public directory in your express app.
Then in your app.js you should have something like:
app.use(express.static('public'));
Its explained here on the express site - http://expressjs.com/starter/static-files.html
Elsewhere
Uncaught ReferenceError: io is not defined
$(document).ready(function(){
var socket=io.connect('http://localhost:3000');
This is because you havent defined io on your client. You call connect on something called io but havent declared/defined io anywhere.
Also
You havent created a socket server on your app side. You should be doing something along the lines of:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
io.on('connection', function (socket) {
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
});
});
Example
Socket.io have an example chat app on github that you should use as reference.
Your chat.js would be the equivalent of their public/main.js
Your chat.jade is equivalent to their public/index.html
and your app.js matches their index.js
i am accessing the script.js and libs.js in index.html like this:
<body style='margin:0px' >
<canvas id='your_canvas'
style='position: absolute; background-color: black;'></canvas>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/libs.js"></script>
<script type="text/javascript" src="/script.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
but the .js files cannot be accessed and showing error:
1) GET script.js 404 (Not Found) localhost/:12.
2) GET libs.js 404 (Not Found) localhost/:11.
3) Uncaught ReferenceError: main is not defined (index):17.
where am i going wrong and how can i include these two JavaScript files using node.js?
my app.js is :
var express = require("express"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io").listen(server);
server.listen(8000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.use(express.static(__dirname + '/public/script.js'));
app.use(express.static(__dirname + '/public/libs.js'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
and then i have my script.js and libs.js files.
You need to actually serve these files if you want them to be accessible. You can't just include them in your project directory. If you are using Express, you can designate a static file directory like this:
app.use(express.static(__dirname + '/public'));
You can also use node-static or even create a handler for each file...
Using express, your code should look something like this (Not tested):
var express = require("express");
var app = express();
app.server = require('http').createServer(app);
var io = require("socket.io").listen(app.server);
app.get('/', function(req, res){
res.sendfile(__dirname + '/public/index.html'); // I would move this file to public
});
app.use(express.static(__dirname + '/public'));
io.sockets.on('connection', function(socket) {
socket.on('send coordinates',function(data){
io.sockets.emit('coordinates', data);
});
});
app.server.listen(8000);
Are you trying to call:
<script>
jQuery(function($){
main(); //this function is inside of script.js
});
</script>
If you are then you need to save your code as a file named script.js in the root directory. Adding javascript/jQuery between tags in your html does not need to be called and will run automatically.
I'd advise laying your script out in the following way too, i don't recognize the way you have laid it out.
<script>
var main = function() {
\\Your javascript/jQuery
}
$(document).ready(main);
</script>