Failed to load resource socket.io - javascript

I am trying to use in socket.io in my node.js app, but my client can't get the library from my sever and I don't know why.
Error: Failed to load resource: the server responded with a http://localhost:3000/socket.io/socket.io.js status of 404 (Not Found)
Server site:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
io.on('connection', function(socket){
console.log('a user connected');
});
Client side:
<head>
<link rel="stylesheet" href="/stylesheets/style.css" />
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</head>

Your index.html code couldn't find socket.io because you are sendig only Index.html for response. Please try following code.
Use following code:
//"client" is folder for client code which contains index.html
app.use(express.static(__dirname + '/client'));
Remove following code. Node.js will find index.html automatically.
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
});
Change your index.html
New code:
<script src="https://cdn.socket.io/socket.io-1.3.7.js"></script>
Old code:
<script src="/socket.io/socket.io.js"></script>

I don't know exactly why your code isn't working, but if socket.io is installed properly, then it automatically configures a route in Express to serve the request for /socket.io/socket.io.js. So, apparently socket.io is not configured/installed properly in your situation.
I can tell you that this initialization of Express and socket.io works and does not have the problem you speak of:
var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io')(server);

I had the same problem in my index.html while learning Node.js.
The console prompted similar error
I removed socket.io module by executing npm r socket.io in my project directory and re-installed it using npm i socket.io and then it worked fine.

Related

Error :Enoent :no such file or directory ,stat 'D:\awesome-testindex.html'

I have a folder named awesome test and it contains index.hml ,node modules and server.js .Here is the server.js file and i am getting this error .
//grab express
var express=require('express');
//create an express App
var app=express();
// create an express route for the home page
// http://localhost:8080/
app.get('/', function(req, res) {
res.sendFile(__dirname + 'index.html');
});
// start the server on port 8080
app.listen(8080);
// send a message
console.log('Server has started!');
Here's where the error is:
res.sendFile(__dirname + 'index.html');
It should be:
res.sendFile(__dirname + '/index.html');
The reason for this is because the index.html is being added upon the directory, which doesn't end with a / by default. You need to add it yourself as shown above.
Hope this helps!
Edit: I tried Node.js before. I think it would be best if you added a "public" folder, with the .js file being above everything. Here's an example:
This was my code for my first Node.js server, as a reference:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const express = require('express');
const app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(3000, () => console.log("Example app listening on port 3000!"))
console.log("http://"+hostname+":"+port)
Note: To use express as shown above, you'll have to open a command line, and type in the following (assuming you have node.js installed correctly):
npm install -g express
Also, to make sure you installed both node.js, do the following:
Node: node -v
Hope everything helps! ^_^

Why am I not receiving a console.log that a new socket user has connected?

I'm more or less following the socket.io documentation and trying to apply it to my slightly different project but I believe I'm making some mistake. I've used express-generator to create my project's skeleton and therefore I got app.js file, www file and route files.
I've put this code in www file:
var io = require('socket.io')(http);
console.log('Socket is running!');
io.on('connection', function(socket){
console.log('A User Has Connected: ' + socket.id);
});
This code in my footer file:
<script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-3.2.1.min.js"></script>
<script src="/javascripts/javascript.js"></script>
</body>
</html>
And this in my JavaScript file:
$(document).ready(function(){
var socket = io();
});
Now I understand that when a request is made, the console should log "A User Has Connected: " + the id of the socket but I'm not getting anything other than "Socket is running!". I assume I'm missing something but can't figure it out and the documentation is using the same code.
var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
You have to use the same server instance express-generator creates, which is the following line in www file
var server = http.createServer(app);
To use that, change
var io = require('socket.io')(http);
to
var io = require('socket.io')(server);

Node.js/Express error: cannot GET /

So I have some code (app.js, in the server)
console.log("Server started. If you're reading this then your computer is still alive."); //Unnecessary test command to make sure everything works.
var express = require("express");
var app = express();
var serv = require("http").Server(app);
app.get("/", function(req, res) {
res.sendFile(__dirname + "/client");
});
app.use("/client", express.static(__dirname + "/client"));
serv.listen(2000);
//Set up server stuff. This isn't touched.
var io = require("socket.io")(serv, {});
io.sockets.on("connection", function(socket) {
console.log("Socket connection"); //This will print to the server, not the developer console in your browser.
});
//Initialize sockets and set up socket listeners. This isn't touched either, except when adding new events.
And some more code:
<!DOCTYPE html>
<html>
<head>
<title>Multiplayer!</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io();
</script>
</body>
</html>
My folder structure is:
multiplayer_game
app.js
package.json
node_modules (folder)
node stuff
client (folder)
index.html
js (folder)
img (folder)
server (folder)
Where the farther in the file is, the more "nested" it is.
When I open the page by doing node app.js (folder already cd'ed) and go to localhost:2000, I get "Cannot GET /". When I go to localhost:2000/client, I get everything fine. What can I do to fix my code?
You will need a router for that.
const router = express.Router;
router.get('/', function(req, res) {
res.sendFile(__dirname + "/client");
});
app.use('/', router);
A middleware is not capable to handle various http methods.

index.html not invoking javascript file

I'm making a simple client/server connection via node.js modules and a simple HTML page.
the html page is this:
<script type="text/javascript" src="index.js"></script>
Where the index.js file in the same directory is this:
alert("hello!");
This works fine when I manually click on the html page, but when I invoke it using my app.js:
var express = require("express");
var app = express();
var server = require('http').Server(app);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/web/index.html');
});
app.use('/web', express.static(__dirname + '/web'));
server.listen(2000);
console.log('Started Server!');
by calling
node app.js
it does not show the alert when the HTML page loads. I just installed node.js and installed the node express dependencies in this app after I called "node init" on the project.
The path for index.js and static folder does not match. Therfore it fails to load index.js.
This should work:
app.use('/', express.static(__dirname + '/web'));
server.listen(2000);

Express Server returns Cannot Get when trying to access index.html

I referred to the previously asked question on this but couldnt resolve it. I have Express server installed and trying to run Index.html file through it.
But I am getting 'Cannot GET /' as the response.
Here is the server.js through which I calling the index.html
var express = require('express');
var app = express();
app.get('index.html', function (req, res) {
app.use("/", express.static(__dirname));
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Thanks in advance!!
When you access a directory on your hosted site, say the root directory of localhost on port 8080, using http://localhost:8080/ for URL, the browser does not send a request for 'index.html` to the server and just uses whatever the server sends back.
It's the express static middleware which in response to a browser request with no filename will check if the folder exists and (by default) return any index.html contained in the folder. So your line of code for routing, app.get('index.html') never executes, and the browser gives you the error message.
Here's a mini static express server if you want to try it.
var express = require('express');
var app = express();
app.use(express.static('../public')); // path to your public directory
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
If you want a simple static, folder-as-server kind of thing, you can do it without express way like "/public":
var fs = require("fs");
var host = "localhost";
var port = 8000;
var express = require("express");
var app = express();
app.use('/', express.static(__dirname));
app.listen(port, host);
I put this in the file express.js, so that is in the same folder than index.html (even associated .js with node.exe). This way the folder is the root of the server.

Categories