Connection to nodejs (express) refused - javascript

I’m a long term programmer, but haven’t used nodejs much in my code. Now I need to use it in my current code and I’ve ran into a problem that I can’t seem to figure out myself, I have googled a lot but nothing seem to fix it.
I am trying to get my website to connect to the nodejs server running on same host.
If I visit the url in my browser, it works fine (http://localhost:6857/socket.io/?EIO=4&transport=polling) and I see this respond
0{"sid":"s_v860SbNO4toknPAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
But when I try to connect thru the website, I just get
GET http://localhost:6857/socket.io/?EIO=3&transport=polling&t=N_gL_HZ net::ERR_CONNECTION_REFUSED
Can someone guide my in the right direction for how to fix this, so I can begin using nodejs inside my website?
This is my server.js
// use express
var express = require("express");
// create instance of express
var app = express();
// use http with instance of express
var http = require("http").createServer(app);
// start the server
var port = 6857;
http.listen(port, '0.0.0.0', function () {
console.log("Listening to port " + port);
});
// create socket instance with http
var io = require("socket.io")(http);
// add listener for new connection
io.on("connection", function (socket) {
// this is socket for each user
console.log("User connected", socket.id);
});
io.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
And this is my JS code inside my website
<script>
var server = "http://localhost:6857/";
var io = io(server);
</script>

Socket IO requires you to enable CORS explicitly - Thus why you get the error stated above.
To enable CORS, please see the following link

Related

Heroku basic http request

I am a beginner and been playing around with some js code.
First I would like to know what this line of code exactly does. Let's assume n is some variable. My understanding was, that it sends a http request to herokuapp with the data of interest "n". How is that data incorporated?
const Http = new XMLHttpRequest();
const url='https://myapp.herokuapp.com/?data='+n;
Http.open("GET", url);
Http.send();
What is the most simple way to accept and log the data n in my heroku app?
Thanks in advance!
The code above sends a HTTP GET request to the application running at myapp.herokuapp.com passing a parameter called data with whatever value the variable n holds.
On Heroku typically you deploy an application (service) than can listen and process HTTP requests. You can use any language (JS, Python, Java, etc..) since they all are suitable to implement a web service.
Using NodeJS you would do something like:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const data = req.query.data // grab parameter
console.log(`Value of data is ${data}`);
res
.status(200)
.send('Ok')
.end();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
Checkout NodeJS on Heroku to see how you setup and deploy a NodeJS application.

Node.js and socket.io thousands of unsuccessful connection attempts

Good evening SO-community, I tried really hard to fix this issue but I think I'll need your wisdom because I really don't know what's the matter here. I have a node.js server which is serving an index.html via express. I am currently starting to use socket.io.
This is the code on my client side:
$( document ).ready(function() {
document.getElementById("start").addEventListener("click", startGame);
function startGame() {
var socket = io(); console.log("Sending request to server");
socket.emit('connectToTable', {tableID: 1});
socket.on('successfulConnection', function(msg){
alert(msg);
}); }
});
This is the code on my server side:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var port = process.env.PORT || 3000;
path = require('path');
app.use(express.static(path.join(__dirname, '/')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("There is someone knocking on the door")
socket.on('connectToTable', function(socket){
console.log("Received player request")
var player = new Player(socket.id);
socket.emit('successfulConnection', "The connection to the server has been successful");
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
On my console on the server I see that "There is someone knocking on the door" gets printed hundreds or thousands of times per second which leads to a CPU load of 100%. At the same time I can see on the client-side (in Chrome) that hundreds of xhr polls are being made.
I really can't figure out why the connection is not established after the first connection attempt and retried sooo often. Furthermore I don't even really understand why it is even using xhr polling instead of websockets.
Help would be very highly appreciated. Thank you so much in advance.
You have to use the same version of socket.io, on the client and on the server (I have had the same problem 5 days ago), check on console with:
npm list socket.io
the version of the server and look if you use the same version on the client, on index.html like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
You can get the url from here:
Versions of socket.io
Regards

socket.io authentification not working on first connection

I have a NodeWebkit client which connects to a nodejs server using the socket.io library (JavaScript).
The client launches the connect procedure on the application start but the server does not acknoledge any connections... Though the client's socket has the connected attribute to "true".
You should know that I am using socketio-jwt to authentificate the connection.
Github: https://github.com/auth0/socketio-jwt
I know that the connection does work in a way because if I add :
io.sockets.on('connection', function(){console.log("hello");})
It prints hello !
So it seems that event though the connection is somehow made it doesn't want to do the auth part with the library, resulting in... Well... Nothing.
But that's not all !!
Because if I reboot the app (not the server) then the auth works most of the time ! It acts like a race condition... But I dont see how it could possibly be one... Every line of code is geting executed appart of the success callback of authentification.
I tried connecting to a remote server and on my localhost.
I also tried with an other library of socket auth but I've got the same probleme.
This is the server code:
var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
io.sockets.on('connection', socketioJwt.authorize({
secret: 'some secret',
timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {
console.log('[Info]: A user connected to socket = ', socket.decoded_token);
});
});
http.listen(5000, function () {
console.log('listening on *:5000');
});
And now the client code:
this.socket = io.connect('http://' + that.hostName +':' + that.port);
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret);
this.socket.on('connect', function () {
that.socket.emit('authenticate', {token: token}) //send the jwt
.on('authenticated', function () {
console.log("[Info]: Socket login successfull");
})
.on('unauthorized', function (msg) {
console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
});
});
The server side log "A user connected to socket" is never shown.
If you have an idear ! Thanks for your time.
Why is there a 'that' on socket.emit (client)? I think you should handle it within the same instance of socket.io - using same 'this' as above

Why node.js requires an upgrade while trying to run an application on the localhost?

When I try to run my node.js application on a localhost server, it does not run and demands a required upgrade. I have tried to run the code but I get the following error:
server code
var WebSocketServer = require('ws').Server,
ws = new WebSocketServer({port: 80}),
CLIENTS=[];
**new connection etablished**
ws.on('connection', function(conn) {
CLIENTS.push(conn);
conn.on('message', function(message) {
console.log('received: %s', message);
sendAll(message);
});
console.log("new connection");
conn.send("NOUVEAU CLIENT CONNECTE");
**if you close connection**
conn.on('close', function() {
console.log("connection closed");
CLIENTS.splice(CLIENTS.indexOf(conn), 1);
});
});
**send messeages vers all clients**
function sendAll (message) {
for (var i=0; i<CLIENTS.length; i++) {
var j=i+1;
CLIENTS[i].send("Message pour le client "+j+": "+message);
}
}
client code
<p>
Result :<output name="" type="text" id="result" value"readonly"></output>
</p>
<input type="text" onchange="ws.send(this.value);">
</body>
<script>
var ws =new WebSocket('ws://localhost:80');
ws.onmessage=function(event){
document.getElementById("result").value=event.data;
}
</script>
Upgrade Required is a reference to the header that is sent when establishing a WebSocket connection between a client (i.e. the browser) and the server.
Like #Prinzhorn stated in his comment, you need a client application that connects to your WebSockets server, which could be a static html page. I recommend you reading this introduction to websockets to understand better how WebSockets work.
Do not open a client HTML file as a localhost URL but open the file directly.
After running your web-socket server,
localhost:[port]/client.html -> you will get the message "upgrade required".
file:///[folder]/client.html -> you can see your HTML file.
because you don't have any web-server with a web-socket or you did not configure your web server for your web-socket. So, you should use your file system.
The easiest way is to use right click on the client file and open it with your favorite browser.
You need to combine your WebSocket based server and static html generator Express.
For example
var express = require('express')
var expressWs = require('express-ws')
var app = express()
expressWs(app)
app.ws('/echo', (ws, req) => {
ws.on('connection', function (connection) {
//...
})
ws.on('close', function () {
//...
})
})
app.use(express.static('public'))
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
In client code
var ws = new WebSocket('ws://localhost:3000/echo');
ws.onmessage=function(event){
document.getElementById("result").value=event.data;
}
The issue is that your web socket server is running on port 80, so when you open the html template using your browser, you are actually opening the web socket server. This is because web pages opening in the browser default to using port 80.
To fix this set your web socket server's port to something else like 3000.
ws = new WebSocketServer({port: 3000})
Then when you open the page in the browser it will open the actual html page instead of the web socket server.

Connecting client to server using Socket.io

I'm relatively new to node.js and it's addons, so this is probably a beginnersquestion.
I'm trying to get a simple HTML page on a webserver connect to a different server running node.js with websocket.io.
My code looks like this:
Client
<script src="socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket();
socket.connect('http://127.0.0.1:8080');
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
Serverside
// Require HTTP module (to start server) and Socket.IO
var http = require('http');
var io = require('socket.io');
var port = 8080;
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(port);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
console.log('Connection to client established');
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
console.log('Server running at http://127.0.0.1:' + port + '/');
Starting up the server works fine and running http://localhost:8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.
But when I run it, nothing happens and the Chrome console returns:
Failed to load resource http://undefined/socket.io/1/?t=1333119551736
Failed to load resource http://undefined/socket.io/1/?t=1333119551735
I've been at this all day. Any help?
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080 with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
You need to make sure that you add forward slash before your link to socket.io:
<script src="/socket.io/socket.io.js"></script>
Then in the view/controller just do:
var socket = io.connect()
That should solve your problem.
Instead of:
var socket = new io.Socket();
Try:
const socket = io();
Also add a server file:
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
const io = require('socket.io')(server);
const PORT = 5000;
server.listen(PORT, () => {
console.log(`Server is Listening On Port ${PORT}`);
});

Categories