I have below folder structure in VS2015:
The server.js has below code:
var express = require('express')
var app = express();
var http = require('http').Server(app);
var path = require('path');
var port = process.env.port || 1337;
app.use(express.static(__dirname + 'client'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'client', 'HTML1.html'));
});
http.listen(port, function () {
console.log(`listning on ${port}`);
})
and Html1.Html has below code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head data-ng-app="imageLoaderApp">
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
</div>
<script src="/client/scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope) {
console.log(`i'm here.'`);
});
</script>
</body>
</html>
When I'm hitting below url in browser
http://localhost:1337/
I'm getting below error in console:
This is happening with all the js files. I even tried to move the html and js files in main folder still getting the same error.
What am I doing wrong?
It looks like HTML1.html is in the client folder. If that is the case I think you need to put the path to the js relative to it so: 'src="scripts/angular.js"'
Related
I am trying to send some json object from the server side to the client side.
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function(json) {
io.send('message', json);
});
app.listen(3000);
and on index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data) {
console.log(data);
});
</script>
</body>
</html>
I keep getting this error
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?
EIO=2&transport=polling&t=1602487581123-0' from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Use "socket.io": "^2.3.0", for server side, change server side code to following:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function() {
io.send('message', json);
});
http.listen(3000, () => console.log('HTTP server is listening on port 3000'));
For the CORS header, any origins being allowed by default.
And I recommend you use the latest version of socket.io for the client-side. You can use this CDN.
client side:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js" integrity="sha512-AcZyhRP/tbAEsXCCGlziPun5iFvcSUpEz2jKkx0blkYKbxU81F+iq8FURwPn1sYFeksJ+sDDrI5XujsqSobWdQ==" crossorigin="anonymous"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data, json) {
console.log(data, json);
});
</script>
</body>
</html>
Create HTTP Server for client-side:
☁ 64313396 [master] ⚡ http-server -p 3001
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:3001
http://172.31.160.227:3001
http://10.23.128.81:3001
The output of browser console:
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>
I am new to NodeJS and socket.io. I just intend to detect a socket connected to the Express server. It was working fine for me when I was not using Express server.
Then for some reason I used Express and wanted everything to be static so I added this line to the Server File.
app.use(express.static(__dirname));
The above line disturbs my client.html file. Below is the code for my client.html. I debugged it using developer console and found that the script src containing "/socket.io/socket.io.js" is not valid.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="/socket.io/socket.io.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/css/style.css"/>
<title>Untitled Document</title>
<script>
var socket = io.connect();
socket.on('connect',function(){
console.log("socket.io working");
});
</script>
</head>
</html>
What concept or thing am I missing?
For more info: This is my directory structure of the application.
-MyChatRoom
--ChatServer.js
--html
----client.html
--css
----style.css
--images
--node_modules
----socket.io
----express
Edited
For better understanding here is my ChatServer.js code
fs = require('fs');
url = require('url');
express = require('express');
app = express();
server = require('http').createServer(app);
socketio = require('socket.io')(server);
//The root and all subs are made static
app.use(express.static(__dirname));
app.get('/',function(request,response){
response.sendFile(__dirname + "/html/index.html");
});
app.listen(3000);
var connectedUsers = 0;
socketio.on('connection',function(socket){
connectedUsers++;
console.log('client connected');
});
app.listen(3000);
should be
server.listen(3000);
You need to listen on the http module not the express one.
Express is passed through the http module when you instantiate it. Socket.io uses the http module, this is why you need to listen on this to get it to work.
I am new to Node.js.
I have my NodeServer.js file which has below code.
var express = require("express");
var app = express();
var port = 60000;
var io = require('socket.io').listen(app.listen(port));
console.log("Listening on port " + port);
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
When I run this from command prompt , by below code
D:\Path to my application>Node NodeServer.js
It shows message like
info - socket.io started
Listening on port 60000
But when I try to connect to this port from browser by http://127.0.0.1:60000, it shows me below error in command prompt
D:\Path to my application\node_modules\expres
s\lib\application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot call method 'handle' of undefined
What am I Doing wrong?
Above issue is solved:
Below is my EDIT
Below is my client Script
$(document).ready(function () {
var socket = io.connect('http://127.0.0.1:60000');
});
Below is my desing
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="http://127.0.0.1:60000/socket.io/socket.io.js" type="text/javascript"></script>
<script src="NodeClient.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
When I run my application I get error of "NetworkError: 404 Not Found - http://127.0.0.1:60000/socket.io/socket.io.js"
I have solved my issue by below steps.
I moved my ClientScript to one specific folder(Scripts).(Say my client Script's name is NodeClient.js)
I removed app.get("/", function(req,res){ your logic should go here }); function from Server script.
added below code app.use(express.static(__dirname + '/Scripts'));
Now it is working the way I want.
I don't know whether it is right way or not, but it is working now for me.
change the following line
var io = require('socket.io').listen(app.listen(port));
by
var io = require('socket.io').listen(port);
app.listen(port) returns an object but we have to run the socket.io and express in same port. To do that simply pass the port variable
I dont get why this does not work:
I have a sample.js containing:
var http = require('http');
var socket = require('socket.io');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
io.sockets.on('connection', function(client) {
console.log('Client Connected...');
client.emit('messages', {hello: 'world'});
});
server.listen(8080);
I have an index.html page that contains:
<!DOCTYPE html>
<html>
<head>
<script src="socket.io.js"></script>
<script>
var server = io.connect('http://mydomain:8080');
server.on('messages', function(data) {
alert(data.hello);
});
</script>
</head>
<body>
</body>
</html>
Update: When using the socket.io-client.js library, when I go to the http://mydomain:8080 page, I get an "info - unhandled socket.io url"
Can someone point out what I may be doing wrong?
Your server's never sending out index.html because you never told it to. You need something like:
app.get('/', function(req, res) {
res.sendfile('index.html');
});
assuming index.html is at the root level of your app, or, more generally:
app.use(express.static(__DIRNAME+'/public'));
and then put index.html (along with any other static files like stylesheets) in the public subdirectory of your app.