I am getting get polling-xhr.js:157 404 error on my website - socket.io

I am using server.js code
const { startCon } = require('./server/WaConnection')
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
const router = express.Router();
const { Server } = require('socket.io');
const io = new Server(server);
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: '50mb', parameterLimit: 1000000 }))
app.use(router);
require('./server/Routes')(router)
io.on('connection', (socket) => {
socket.on('StartConnection', async (device) => {
startCon(device, socket)
return;
})
socket.on('LogoutDevice', (device) => {
startCon(device, socket, true)
return
})
})
server.listen(process.env.PORT_NODE, () => {
console.log(`Server running on port ${process.env.PORT_NODE}`);
})
I am getting the error again and again that
enter image description here
I will be very thank full if you reslove my issue

Related

HTTPS Stream with websockets / Socket.IO (MERN)

Hi I am wondering how I get this behavior:
There is a Button which starts the stream of a specific DIV (already worked using HTTP).
The Stream should be encrypted using HTTPS on localhost.
I changed the connection to HTTPS, created a key and a certificate with this command:openssl req nodes new x509 keyout server.key out server.cert. In the Chrome Dev Tool / Network Section I receive this:
Chrome Screenshot
BUT: the part on the server where I log that a user connected successfully isn't executed and I can't figure out why.
my react component:
import React, { useEffect, useState, useRef } from 'react';
import html2canvas from 'html2canvas';
import io from 'socket.io-client';
const socket = io('https://localhost:8080', {
transports: ['websocket'],
cors: {
origin: 'http://localhost:3000',
},
});
function Stream() {
const [message, setMessage] = useState("Streaming: OFF");
const [streaming, setStreaming] = useState(false);
const sectionRef = useRef(null);
useEffect(() => {
if (!streaming) return;
const intervalId = setInterval(() => {
html2canvas(sectionRef.current).then(canvas => {
socket.emit("streaming", canvas.toDataURL("image/webp"));
});
}, 40);
return () => {
clearInterval(intervalId);
};
}, [streaming]);
const startStream = () => {
setMessage("Streaming: ON");
setStreaming(true);
};
const stopStream = () => {
setMessage("Streaming: OFF");
setStreaming(false);
};
return (
<div>
<h2>Anchor:</h2>
<button onClick={startStream} disabled={streaming}>Start streaming</button>
<button onClick={stopStream} disabled={!streaming}>Stop streaming</button>
<p>{message}</p>
<div ref={sectionRef}>
{/* Replace this with the section of the website you want to stream */}
<p>This is the section of the website that will be streamed</p>
</div>
</div>
);
}
export default Stream;
and the server looks like this:
const https = require('https');
const fs = require('fs');
const cors2 = require('cors');
const options = {
key: fs.readFileSync(\__dirname + '/server.key'),
cert: fs.readFileSync(\__dirname + '/server.cert')
};
const server = https.createServer(options);
const io = require('socket.io')(server);
io.use(cors2({
origin: "\*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
allowedHeaders: "Content-Type,Authorization"
}));
io.on('connection', (socket) =\> {
console.log('a user connected');
socket.on('streaming', (data) =\> {
console.log("received streaming data: ", data);
io.emit('streaming', data);
});
});
server.listen(8080, () =\> console.log('listening on '));
changed browser to Firefox, activated chrome://flags/#allow-insecure-localhost

socket.io not working once deployed on 000webhost

I read through other post with similar issue which I couldn't solve. I created a simple chat using socket.io, express. On the localhost its working but not on the 000webhost. I'm probably missing a code somewhere.
Tried adding line of codes on the server file and the client side but still couldn't get it to run.
server side
const express = require("express");
const Socket = require("socket.io");
const app = express();
const server = require("http").createServer(app);
const io = Socket(server, {
cors: {
origin: "*",
method: ["GET", "POST"]
}
})
let PORT = 5000;
server.listen(PORT, () => {
console.log("listening on port: ", PORT)
})
const users = [];
io.on("connection", (socket) => {
console.log("connected to", socket.id)
socket.on("adduser", (username)=>{
socket.user = username;
users.push(username);
io.sockets.emit("users", users)
})
socket.on("message", (message)=>{
io.sockets.emit("message_client", {
message,
user: socket.user
})
})
socket.on("disconnect", () => {
console.log("we are disconnecting...: ", socket.user)
if (socket.user){
users.splice(users.indexOf(socket.user), 1)
io.sockets.emit("users", users);
console.log('remaining users: ', users)
}
})
})

SocketIO 4 - won't emit to the room

I have following server code:
const path = require("path");
const http = require("http");
const express = require("express");
const {instrument} = require('#socket.io/admin-ui')
const {jwtDecode, jwtVerify, resignJwt} = require('jwt-js-decode')
const secret =
"xxxxxxx";
const app = express()
const server = http.createServer(app)
const io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io", "http://localhost:3001"],
credentials: true
},
});
let servantID = ''
io.use((socket, next) => {
const header = socket.handshake.headers["authorization"];
jwtVerify(header, secret).then((res) => {
if (res === true)
{
const jwt = jwtDecode(header);
servantID = jwt.payload.iss;
return next()
}
return next(new Error("authentication error"));
});
});
instrument(io, { auth: false });
server.listen(3000, () =>
console.log('connected')
)
io.on('connection', socket => {
socket.on("join", (room, cb) => {
console.log('Joined ' + room);
socket.join(room);
cb(`Joined the best room ${room}`)
});
socket.on('newOrder', function (data) {
socket.to('servant').emit('this', data);
console.log(data);
})
socket.on("thisNew", function (data) {
console.log('this new');
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
And client side code:
socket.emit('join', 'servant', message => {
console.log(message)
})
socket.on('this', () => {
console.log('this event')
})
socket.emit('newOrder', 'data')
When I emit like this:
socket.to('servant').emit('this', data);
the client doesn't receive anything, but if I emit without room:
socket.emit('this', data);
the event and data are received on the client side.
What am I doing wrong here?

koa2 post always show Method Not Allowed?

//server.js
const Koa = require('koa')
const app = new Koa();
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
const Router = require('koa-router');
const fs = require('fs');
const router = new Router();
const UserController = require('./server/controller/user.js');
const checkToken = require('./server/token/checkToken.js');
router.get('/user/login', async ctx => {
ctx.body = JSON.parse(fs.readFileSync( './pass.json'));
console.log(ctx.body);
});
router.post('/signin', async (ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p>Try again</p>`;
}
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(8090, () => {
console.log('The server is running at http://localhost:' + 8090);
});
koa:2.52
koa-bodyparse:4.21
koa-router:7.4
when I type http://localhost:8090/user/login can get the Json data,but type http://localhost:8090/signin always show 405 Methods Not Allowed ,(debian firefxo) show Request Method "GET",response Allow: POST,Connection: "keep-alive"
I hope get your help.
I guess you shouldn't use the chrome to do the post cause when you type some url, the default method is GET not POST, you can check it out from the NETwork。 Try postman it will work.Sorry for my bad english,I hope it will help XD

Angular 2 cli project -Socket.io not working

Folks,
I have a angular 2 Cli project. Its a simple chatting application. But for some reasons, server is not receiving/sending message to client. There is no compile error and app works but no socket messaging.
Below is the code snippet from each:
Express:
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
//set socket.io for chat
var io = require('socket.io').listen(server);
io.on('connnection', (socket) => {
console.log('user connected');
socket.on('message', (msg) => {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
socket.on('disconnect', () => {
console.log('user has disconnected');
});
});
server.listen(port, () => console.log("server running"));
App component
import { Component } from '#angular/core';
import * as io from "socket.io-client";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
messages: Array<String>;
chatBox: String;
socket: any;
constructor() {
this.chatBox = "";
this.socket = io("http://localhost:3000");
this.socket.on("message", (msg) => {
this.messages.push(msg);
});
}
send(message) {
this.socket.emit("message", message);
this.chatBox = "";
}
}
Html:
<ul>
<li *ngFor="let item of messages">{{item}}</li>
</ul>
<input [(ngModel)]="chatBox" autocomplete="off" />
<button (click)="send(chatBox)">Send</button>
I would appreciate any help or hint to resolve this.
If I simple express based server with html chatting works fine.
Thanks
There's no code for connection to socket at all.
Change
this.socket = io("http://localhost:3000");
to
this.socket=io.connect("http://localhost:3000")

Resources