How to connect react-native to peerjs server on heroku - node.js

how to use PeerServer deployed on heroku, in react native
I watched a youtube tutorial where tutor connected his react-native app with peerserver on localhost:5000 and that worked. However, my peerserver is deployed on heroku, trying to connect my app to it the same way the tutor did isn't working. I get the error [Error: Could not get an ID from the server.] which comes from peerServer.on('error', console.log)
This is my react-native code
export const API_URI = 'https://mvmserver.herokuapp.com'
// Peer Config
const peerServer = new Peer(undefined, {
host: 'mvmserver.herokuapp.com',
secure: false,
port: 52129,
path: '/mypeer'
})
peerServer.on('error', console.log)
// Socket config
export const socket = IO(`${API_URI}`, {
forceNew: true
})
socket.on('connection', () => console.log('Connected client'))
This is how the tutor had his
export const API_URI = 'localhost:5000'
// Peer Config
const peerServer = new Peer(undefined, {
host: '192.00.0.0.0',
secure: false,
port: 5000,
path: '/mypeer'
})
peerServer.on('error', console.log)
// Socket config
export const socket = IO(`${API_URI}`, {
forceNew: true
})
socket.on('connection', () => console.log('Connected client'))
My peerserver.js on heroku
const express = require('express')
const http = require('http')
const socketio = require('socket.io')
const {ExpressPeerServer} = require('peer');
const app = express();
const server = http.createServer(app)
const io = socketio(server).sockets
//Borderparser
app.use(express.json())
const customGenerationFunction = () => (Math.random().toString(36) + "0000000000000000000").substr(2, 16)
const peerServer = ExpressPeerServer(server, {
debug: true,
path: '/',
genderateClientId: customGenerationFunction
})
app.use("/mypeer", peerServer)
io.on('connection', function(socket) {
console.log('connected')
socke.on('join-room', ({roomID, userId}) => {
socket.join(roomID)
socket.to(roomID).broadcast.emit('user-connected', userId)
})
})
const port = process.env.PORT || 5000
server.listen(port, () => console.log(`Server is running on port ${port}`))

Related

MongoParseError: mongodb+srv URI cannot have port number

i have the following code
database.js file
const mongoose = require('mongoose');
const { MONGO_URI } = process.env;
exports.connect = () => {
// lets connect our database
mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
}).then(() =>{
console.log('connected to the database')
}).catch((error) =>{
console.log('connection to the database failed');
console.error(error);
process.exit(1);
});
};
index.js file
const http = require('http');
const app = require('./app');
const server = http.createServer(app);
const { API_PORT } = process.env;
const port = process.env.PORT || API_PORT;
server.listen(port, () => {
console.log(`server is running on port ${port}`)
})
when i run my index.js file i get an error
server is running on port 4001
connection to the database failed
MongoParseError: mongodb+srv URI cannot have port number
My .env file (note:password and name is made up)
API_PORT=4001
MONGO_URI=mongodb+srv://dwin:#12345#cluster0.3qohzms.mongodb.net/?retryWrites=true&w=majority
what coulb be wrong with the above code?

How to resolve server error in Socket.io?

I am creating a web application, using socket.io . A Server error occurred while connecting to the server. We found out that the error is in the backend. What could be written incorrectly here? Code:
const path = require('path');
const express = require('express');
const app = express();
const fs = require("fs");
var privateKey = fs.readFileSync('path').toString();
var certificate = fs.readFileSync('path').toString();
const http = require('https').Server({key:privateKey,cert:certificate}, app);
const io = require('socket.io')(http);
const port = 9998;
const debug = true;
var connectedArray = new Array()
const delay = 60 * 1000
const mysql = require('mysql2');
const db = mysql.createConnection({
host: 'localhost',
user: 'user_name',
password: 'user_password',
database: 'database',
});
io.on('connection', (socket) => {
socket.on('register', msg => {
console.log("User registered")
connectedArray.push({
connectmessage: msg,
socket: socket,
})
})
socket.on('disconnect', () => {
if (debug) console.log('User disconnected')
})
})
app.use(express.static(path.resolve(__dirname, 'static')))
app.get('/', (req, res) => {
res.sendFile('./index.html')
})
http.listen(port, () => {
console.log(`Server started listening on port ${port}...`)
})
P.S: The problem began to arise after binding the domain
P.S 2: I have two sites on server, on different Apache virtual hosts
P.S 3: I am using https

socket.io problems. Not able to connect. front end says connection: false and backend doesn't log anything

i am new to socket.io and i can't get it to connect to react app. here is my app.js in node
const express = require('express');
const port = process.env.PORT || 4000;
const router = require('./routes/routes');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
const db = require('./db/db');
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => {
console.log('connected');
});
app.use('*', cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
(router);
app.listen(port, () => {
console.log('listening on port ' + port);
db.sync({
// force: true,
logging: false,
});
});
and my front end code.
import React, { useState, useEffect, useRef } from 'react';
import { io } from 'socket.io-client';
import classes from './Chatroom.module.css';
const Chatroom = ({ user, getAllMessages, setGetAllMessages }) => {
const ENDPOINT = 'http://localhost:4000/getallmessages';
var socket = io(ENDPOINT);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
socket.on('connect', () => {
socket.send('hello');
console.log('connected.');
});
console.log(socket);
}, []);
Whenever i look in the console on it shows connected: false and nothing is logging on the backend.
In order to fix the issue i had to add options to my io declaration as follows.
const server = require('http').createServer(app);
const options = {
cors: true,
origins: ['http://127.0.0.1:3000'],
};
const io = require('socket.io')(server, options);
127.0.0.1 being home and on client side my server is on 3000 so that's where that comes from. and on the client side you were right i had to remove "getallmessages" route so now it is as follows.
onst ENDPOINT = 'http://localhost:4000/';
var socket = io(ENDPOINT);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
socket.on('connect', () => {
socket.send('hello');
console.log('connected.');
});
console.log(socket);
}, []);
socket.io is bound to the server object so you should listen to the server instead of the app.
Change app.listen to server.listen
Change endpoint by removing getallmessages if you are not using namespaces

socket io on connection not firing

I'm using socket.io-redis and it doesn't seem like it's connected... I tried with my client application and with socketio-client-tool, but I'm not getting any connections. here's my code:
index.js
const express = require('express');
const app = express();
const server = require('http').createServer(app);
require('./socket/socket')(server);
module.exports = server.listen(4000, () => logger.info(`Listening on port 4000`));
socket.js
module.exports = function (server) {
const _io = io(server);
const redisConnection = redisAdapter({ host: 'localHost', port: 6379 });
logger.info('connected to redis');
_io.adapter(redisConnection);
logger.info(`connected to socket.io`);
_io.on('connection', (socket) => {
console.log('a user connected');
});
};
I'm using ngrok to access the backend. Not sure if that has to do...

i cant get the data from PostgreSQL and display it in node JS

index.js
const { Client } =require('pg');
const client = new Client ({
user: 'postgres',
host: 'localhost',
database: 'test',
password: 'admin',
port: 5432,
});
client.connect();
module.exports.myconnection = client;
app.js
const express = require("express");
const port = 3000;
const app =express();
const db =require("./db");
app.use(express.json());
const interactrouter = require("./routes/interactions");
app.use("/data",interactrouter);
app.listen(port, () =>
console.log(`Server running at http://localhost:${port}`) // not single cotaions above tab
);
interactions.js
const express = require ('express')
const router = express.Router()
const db =require('../db')
const { Client } = require('pg')
const client = new Client()
router.get('/',(req,res) => {
client.query("SELECT id, decription, drugcode, diseasecode, type FROM interactions;")
.then (rows =>{
console.log(rows);
res.json(rows)
})
.catch(error => {
console.log(error)
})
})
module.exports =router;
my problem I connect to the server but I can't get the data from the database and this is my code how can I fix it thank you all
so how can I fix it or what I should edit I'm new in this field

Resources