I can't connect socket io on my flutter app - express

I use socket-io-client: 2.0.1 and node server socket io: 4.4.1
but I have got the bellow error
"WebSocketException: Connection to url was not upgraded to websocket"
How can I fix this issue?
Thank you in advance.
my code is :
express node server side code
const io = socketio(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
},
transports: ['websocket']
});
flutter app client code
IO.Socket socket = IO.io(API_HOST, <String, dynamic>{
'transports': ['websocket', 'pooling'],
'autoConnect': false,
});
socket.connect();
socket.onError((data) => {print("$data")});

Related

Backend api call not working in Vue(front)

My environment
front - windows, port 3000
backend - linux (ubuntu) in docker container, port 5000
Vue(front) tsconfig.json
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
server: {
host: true,
port: 3000,
proxy: {
"/api": {
target: "http://127.0.0.1:5000",
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
});
front api call code
const response = await axios.post("http://127.0.0.1:5000/users/login?email=" + code);
backend(Nestjs) - main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: 'http://localhost:3000',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
await app.listen(5000);
}
bootstrap();
I expect the api call to go to the backend, localhost:5000
but i get a 404 error
When I tried with postman, I got normal return, but when I sent the request using axios in Vue with the same request, I got 404 not found.
The most incomprehensible thing is that with the current settings, it was normally requested when developing in the past.
I don't know how to fix this
please help a lot
Repositories currently being edited: https://github.com/PracticeofEno/ft_transcendence
thanks
omg... I send POST message..
But api is GET Message

nestjs: ws:// works but wss://localhost:port/ got ‘WebSocket connection to 'wss://localhost:10086/' failed: ‘

i was trying to create wss server in using nestjs,but when i finished all configuration in a new nestjs project and tried to connect to the server via 'wss://localhost:port', i got the error below:
WebSocket connection to 'wss://localhost:10033/' failed:
enter image description here
and the main.ts is like this:
async function bootstrap() {
const {key, cert} = await readKeyAndCert()
const app = await NestFactory.create(AppModule, {
httpsOptions: {
requestCert: false,
rejectUnauthorized: false,
key,cert
}
});
app.enableCors()
app.useWebSocketAdapter(new WsAdapter(app))
app.useGlobalFilters(
new HttpExceptionFilter()
)
await app.listen(HTTP_PORT);
}
what can i do to fix the wss:// connection?

Websocket fails after implementing CloudFlare

I have implemented cloudflare on a live website, the website has a socket server that's setup with socket.io and express, everything were working fine before implementing cloudflare
Currently I'm using port: 2053 which i've allowed access to through Laravel forge
socket.js
var app = require('express')();
const fs = require('fs');
var server = require('https').createServer({
key: fs.readFileSync('/etc/nginx/ssl/mywebsite.com/1234/server.key'),
cert: fs.readFileSync('/etc/nginx/ssl/mywebsite.com/1234/server.crt'),
}, app);
var io = require('socket.io')(server, {
cors: {
origin: function(origin, fn) {
if (origin === "http://mywebsite.test" || origin === "https://mywebsite.com") {
return fn(null, origin);
}
return fn('Error Invalid domain');
},
methods: ['GET', 'POST'],
'reconnect': true
},
});
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('asset-channel', () => {
console.log('asset-channel: started');
});
redis.on('message', function(channel, message) {
var message = JSON.parse(message);
io.to(message.data.id).emit(channel + ':' +message.event + ':'+ message.data.id, message.data);
});
io.on("connection", (socket) => {
socket.on("join:", (data) => {
socket.join(data.id);
});
socket.on("leave:", (data) => {
socket.leave(data.id);
});
});
server.listen(2053, () => {
console.log('Server is running!');
});
app.js
if (! window.hasOwnProperty('io')) {
// if (
// window.origin === "http://mywebsite.test" ||
// window.origin === "https://mywebsite.com" ||
// window.origin == "https://mywebsite.test"
// ) {
window.io = io.connect(`${window.origin}:2053`);
window.io.on('connection');
// }
}
As mentioned before everything were working fine before implementing cloudflare and i have tried to read some different documentation like:
https://developers.cloudflare.com/cloudflare-one/policies/zero-trust/cors
https://socket.io/docs/v4/handling-cors/
I found many different problems similar online, and tried several solutions but nothing seem to make the socket connection work
Tried to allow all cors like so:
var io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ['GET', 'POST'],
'reconnect': true
},
});
Didn't work either, tried configure some stuff in nginx which didn't work either
Error
Access to XMLHttpRequest at 'https://mywebsite.com:2053/socket.io/?EIO=4&transport=polling&t=NurmHmi' from origin 'https://mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I think i might have to configure something in the cloudflare dashboard, i just dont know what and my googling skills could not take me to the finish line this time around.
Im not too experienced with sockets so it would be awesome if there are some skilled socket expert who have had this issue before who can guide me in the correct direction? :)
I made it run by adding this to the app.js:
window.io = io.connect(`${window.origin}:2053`, { transports: ["websocket"] });
Apparently it will try to use polling instead of websocket.

zeit-now v2 + apollo-server-express: playground error: Server cannot be reached

Currently I am trying to get an api for my nextjs project to work.
For deployment I am using zeit's NOW v2 (locally via "now dev").
Everything works fine except the graphql-server.
In playground and via client I get an 404-error.
Queries are getting executed correctly, but I get an error-object(query results are in the response-field; 404).
Checking it in the playground-gui: same problem and in the playground-input field showing the message "Server cannot be reached".
Playground Initial Error:
{
"error": "Response not successful: Received status code 404"
}
Playground after hello-query:
{
"error": {
"data": {
"hello": "Hello world!"
}
}
}
Browser-Console Playground:
Error: "Response not successful: Received status code 404"
This is my graphql-server loaded with now:
import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
const server = new ApolloServer({ typeDefs, resolvers,
introspection: true, playground: true,
subscriptions: {path: '/api'},
});
const app = express();
server.applyMiddleware({ app, path: "/api", cors: true });
module.exports = app;
Also tried this example. Same problem.
Can anyone tell me how to get it running properly?
I had a similar issue (server can't be reached). It was an authorization problem. The GraphQL Playground docs mention the request.credentials setting:
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
playground: {
settings: {
// So that auth works
// Docs: https://github.com/prisma/graphql-playground
['request.credentials']: 'same-origin',
},
},
subscriptions: {path: '/api'}
});

Peerjs keeps loosing connection and user id is lost

I have made an application following a tutorial using peerjs. Everything seems to be working fine except when I make a connection for a video call where I am using peerjs. I have made my own peerjs server which I am running on localhost (right now for testing). Here is the code for the peer server:
const express = require('express');
const path = require('path');
const http = require('http');
const cors = require('cors');
const errorhandler = require('errorhandler');
var ExpressPeerServer = require('peer').ExpressPeerServer;
var options = {
debug: true,
key: 'copycat'
};
var app = express();
var server = http.createServer(app);
var port = process.env.PORT || '3001';
app.set('port', port);
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/peerjs', ExpressPeerServer(server, options));
app.use(errorhandler());
process.on('uncaughtException', function(exc) {
console.error(exc);
});
server.listen(port);
As you can see I am running the app on port 3001. Now following is the script for peerjs connection for a video call:
// PeerJS
// Compatibility shim
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
// PeerJS object
var peer = new Peer(username + roomId, {
host: 'localhost',
path: '/peerjs',
port: 443,
secure: true,
key: 'copycat',
debug: true
});
peer.on('open', function () {
$('#my-id').text(peer.id);
});
// Receiving a call
peer.on('call', function (call) {
// Answer the call automatically (instead of prompting user) for demo purposes
call.answer(window.localStream);
step3(call);
});
peer.on('error', function (err) {
alert(err.message);
// Return to step 2 if error occurs
step2();
});
// Click handlers setup
$(function () {
$('#make-call').click(function () {
// Initiate a call!
var call = peer.call($('#callto-id').val(), window.localStream);
step3(call);
});
$('#end-call').click(function () {
window.existingCall.close();
step2();
});
step1();
});
function step1() {
// Get audio/video stream
navigator.getUserMedia({ audio: true, video: true }, function (stream) {
// Set your video displays
$('#my-video').prop('src', URL.createObjectURL(stream));
window.localStream = stream;
step2();
}, function () { $('#step1-error').show(); });
}
function step2() {
$('#step1, #step3').hide();
$('#step2').show();
}
function step3(call) {
// Hang up on an existing call if present
if (window.existingCall) {
window.existingCall.close();
}
// Wait for stream on the call, then set peer video display
call.on('stream', function (stream) {
$('#second-video').prop('src', URL.createObjectURL(stream));
});
// UI stuff
window.existingCall = call;
$('#second-id').text(call.peer);
call.on('close', step2);
$('#step1, #step2').hide();
$('#step3').show();
}
This is pretty much the example code from peerjs example file on github. What I am confused about is the port value. Inside the options in the above script its port 443. I get the following error in chrome when I try to make a video call:
peer.js:1492 WebSocket connection to 'wss://localhost/peerjs/peerjs?key=peerjs&id=User80925be509c6c606fa21409858f5&token=zz69b3ccyk' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
Socket._startWebSocket # peer.js:1492
Socket.start # peer.js:1481
Peer._initialize # peer.js:1058
Peer # peer.js:962
(anonymous) # 5be509c6c606fa21409858f5:183
peer.js:1741 PeerJS: Socket closed.
peer.js:1741 PeerJS: ERROR Error: Lost connection to server.
peer.js:1555 POST https://localhost/peerjs/peerjs/User80925be509c6c606fa21409858f5/zz69b3ccyk/id?i=0 net::ERR_CONNECTION_REFUSED
Socket._startXhrStream # peer.js:1555
Socket.start # peer.js:1480
Peer._initialize # peer.js:1058
Peer # peer.js:962
(anonymous) # 5be509c6c606fa21409858f5:183
peer.js:1741 PeerJS: ERROR Error: Lost connection to server.
Please advise what am I doing wrong???
If you are using at your local end then use your localport i.e. 3001 else use 443
make object like this
var peer = new Peer(undefined, {
host: 'localhost',
path: '/peerjs',
port: 3001,
secure: true,
key: 'copycat',
debug: true
});