how to include js file in html which is in different folder - node.js

I include following socket js file in my html to communicate on the server
<script src="/socket.io/socket.io.js"></script>
and i write my connection code in user.js file
var socket = io();
socket.on('connect',()=>
{
console.log('connected to the server');
});
socket.on('disconnect',()=>
{
console.log('disconnected to the server');
});
and i include it in my html page using
<script type="text/javascript" src="../routes/users.js"></script>
but it said GET http://localhost:3000/routes/users.js faild

You will have to serve static files from node to get access to it.
There are many libraries that do the same, Express is most used.
In express you can do it like,
const express = require('express');
const http = require('http');
const app = express();
app.use(express.static(path.join(__dirname, '../routes')));
var server = http.createServer(app);
server.listen(3000, () => console.log(`API running on localhost: ` + 3000));
above use of static, will give access to every file that is in routes folder.

Related

Error GET /socket.io/socket.io.js net::ERR_ABORTED 404

I can't solve this error of socket.io it shows in the console
GET /socket.io/socket.io.js net::ERR_ABORTED 404
Refused to execute script from '/socket.io/socket.io.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Uncaught ReferenceError: io is not defined
at script.js:1:14
I made this with node.js
The files are below (main server file is index.js)
index.js
var express = require("express");
var app = express();
var http = require("http");
var server = http.createServer(app);
var { Server } = require("socket.io");
var io = new Server(server);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/style.css", (req, res) => {
res.sendFile(__dirname + "/style.css");
});
app.get("/script.js", (req, res) => {
res.sendFile(__dirname + "/script.js");
});
io.on("connection", (socket) => {
socket.on("chat message", (msg) => {
io.emit("chat message", msg);
});
});
app.listen(3000);
index.html
<!DOCTYPE html>
<html>
<head>
<title>Test Socket.io</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<h1>Test</h1>
</center>
<script src="/socket.io/socket.io.js"></script>
<script src="script.js"></script>
</body>
</html>
style.css
body {
font-family: Arial;
}
script.js
var socket = io();
Help will be appreciated.
Replace this:
app.listen(3000);
with this:
server.listen(3000);
app.listen() creates a new server so the server you're starting is NOT the server that socket.io is hooked to, therefore the socket.io library is not hooked up to that server and when the request for /socket.io/socket.io.js comes in, you don't get the socket.io JS library.
Here's the code for app.listen():
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
You can see that it creates a new server and then calls .listen() on that new server.
Your express code works because app is hooked to the server created by app.listen(), but socket.io is hooked to the server created by:
var server = http.createServer(app);
var io = new Server(server);
which is never started and is not running. So, socket.io is never hooked up to the server that is actually running. Instead, you should just create and start one server and hook both app and socket.io to that one server.

nodejs socket.io not working on localnetwork

I'm trying to implement a chat on my website but I can't make socket.io work on my localnetwork (it works for localhost but I cant access it from another machine).
Server code:
const path = require('path');
const host = '0.0.0.0';
const port = 3000;
const express = require('express');
const app = express();
const cors = require('cors');
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const script = require('./script');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.listen(port, host, function() {
console.log('Running at: ',host,port);
});
app.use(express.static('public'));
app.use(express.json({limit:'1mb'}));
client code:
const socket = io();
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Proflands!</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="client.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body> </body>
</html>
Error i'm getting:
Failed to load resource: the server responded with a status of 404 (Not Found) socket.io.js:1
where I got my code from: https://socket.io/get-started/chat
It works if I use "http://localhost:3000" but I want it to work on whole localnetwork.
as #Lawrence Cherone commented:
changing:
app.listen(port, host, function() {
console.log('Running at: ',host,port);
});
to:
http.listen(port, host, function() {
console.log('Running at: ',host,port);
});
solved the problem.
If you getting the error: 404 (Not Found) socket.io.js: Then the issue is the src path to the socket.io client in:
<script src="/socket.io/socket.io.js"></script>
If you accessing the server from other machines/websites etc, then change that path to an absolute URL to get the client. Otherwise, it is trying to access the socket.io server relatively, being the same server the client is on.
<script src="http://myserver:3000/socket.io/socket.io.js"></script>

Socket.io doesn't correctly attach to http server in express application

I'm pretty new to NodeJS and trying to get Socket.IO running with an Express application. I've tried to stick to the docs and tutorials as close as possible, but in the end, socket.io.js cannot be found on client side.
The server is being started as follows:
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() { debug('...') } );
Routing/serving pages:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
Including socket.io:
var express = require('express');
var http = require('http').Server(express);
var io = require('socket.io')(http);
And in the HTML file, for clients:
<script src="/socket.io/socket.io.js" type="text/javascript">
But when loading the page, this JS-file is never found. I suspect that including socket.io via that previously created http server is somehow wrong... Or am I missing something else?
Update
I just found out that the snipped that includes socket.io is executed before the server is started (first snippet). They're in different files and the server-start one (named www.js) is configured as "start" script in package.json, the other one (websockets.js) required indirectly by that.
If I put
var io = require('socket.io')(server);
at the end of www.js, everything works just fine. But is there a way to do it from websockets.js, which is loaded before, e.g. by a server start callback function?
Try specifying the full path, like this
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
And connect to your server from client side:
var socket = io.connect('http://localhost:8000/');
also check if socket.io module is available in your node_modules directory.

Socket.io polling 404 in Laravel

I am trying to implement a chat app with Socket.io
in to my Laravel app. The chat app works fine on it's own,
but I am having problems to make it work in Laravel.
I try to serve Laravel on port 8000 and the chat server on 8000.
I use Express 4.8.0 and Socket.io 1.0.6, Node 0.10.29 and nodemon for testing.
//server.js:
var express = require('express');
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
http.listen(8000, function () {
console.log('listening on *:8000');
});
app.use('/', express.static(__dirname + '/public'));
app.get("/*", function (req, res){
res.sendFile(__dirname + "/index.php");
});
//client.js:
var socket = io.connect('http://localhost:8000');
//html - dependencies, I tried all these:
<script src="//cdn.socket.io/socket.io-1.0.0.js"></script>
{{ HTML::script('/socket.io/socket.io.js') }}
<script src="http://localhost:8000/socket.io/socket.io.js" ></script>
<script src="{{asset('/socket.io/socket.io.js')}}"></script>
and then for the client side (own code)
{{ HTML::script('js/client.js') }}
The CDN version of Socket.io gives constantly these kinds of logs:
"GET http://localhost:8000/socket.io/?EIO=2&transport=polling&t=1407425555977-15 404 (Not Found)".
The others ones just gives a js file not found log:
"GET http://localhost:8000/socket.io/socket.io.js 404 (Not Found)"
//folder structure:
/public
/js
client.js
/node_modules
server.js
Can anyone see what I can do to make it work?
EDIT
//server.js
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
io.on('connection', function (socket) {
console.log("Connected server");
}
server.listen(8000);
//client.js
var socket;
$(document).ready(function () {
socket = io.connect('http://localhost:8000');
});
//When I typ the global "socket" object in the log it says:
connected: false
disconnected: true
This is because you have set it up incorrectly. I had the same exact problem you did (same errors and basic code layout). You need to do npm install socket.io --save while in the base directory of your page (the same as where your index.php file is located). Then you have to do the same for express (npm install express --save). You also have to change your server code. Change the creation of io from:
var express = require('express');
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
To:
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
Then remove the app.use and app.get as they are no longer needed for how this is going to be done. Then add server.listen(8000); at the end of the server.js. For dependencies, use: <script src="//cdn.socket.io/socket.io-1.0.0.js"></script>. Then, to run your server, go to it in terminal and type node server.js. Then just connect to it with your client. Also, for events, in the server, use:
io.on('connection', function (client) {
client.on('someEvent', function(someVariables){
//Do something with someVariables when the client emits 'someEvent'
io.emit('anEventToClients', someData);
});
client.on('anotherEvent', function(someMoreVariables){
//Do more things with someMoreVariables when the client emits 'anotherEvent'
io.emit('anotherEventToClients', someMoreData);
});
});
And in your client code:
socket.emit('someEvent', variables);
socket.on('anEventToClients', function(something){
//Code when anEventToClient is emitted from the server
});

cannot get client server running using express in node.js

hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).
here is my code for the app(app.js):
var sys = require('sys'),
express = require('express'),
app = express('localhost');
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var socket = require('socket.io').listen(server);
socket.on('connection', function (client){
// new client is here!
setTimeout(function () {
client.send('Waited two seconds!');
}, 2000);
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
and here is my code for the client(client.html):
<html>
<p id="text">socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = new io.Socket(),
text = $('#text');
socket.connect();
socket.on('connect', function () {
text.html('connected');
});
socket.on('message', function (msg) {
text.html(msg);
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
i got most of the code from:
NodeJS + socket.io: simple Client/Server example not working
and the changed it to be compatible with express 3.x
however when i run the server and open my client using chrome it tells me that it is unable
to load resource file:///socket.io/socket.io.js
i have already installed express and socket.io using npm
also i have read through atleast 20 similar posts and have not been able to find an answer
please help me. thank you
socket.io.js file needs to be served from port 3000, like localhost:3000.
So here is what you do change
<script src="/socket.io/socket.io.js"></script> to
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.

Resources