Guys i've been struggled for this past days, from this socket.io setup. I thought there's should be no mistakes on my code. I've followed all tutorial and documentation on how to setup the server for socket.io using node and express. But still when i try to connect to this there are no response from the socket.io. On my client side i try to connect the same url as this server running http://localhost:8090 (FIXED)
SO EVERYTHING IS SET UP! the thing that it won't work is bcs i didn't set the CORS(see my edited code) on the socket instance on the server side.FYI since Socket.IO v3 u need to include the cors property by defining which url that gonna connected to ur socket.
Server Code:
const express = require ('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const db = require("./Connection/pg_pool");
const authentication = require("./Config/auth");
const connectionError = require("./Config/connectionError");
const cors = require('cors');
let port = 8090;
let hostname = 'localhost';
const midtransClient = require('midtrans-client');
const paymentConf = require('./Config/payment');
const { encode } = require('node-encoder');
const axios = require('axios');
let payment = paymentConf.paymentConf;
let errorMsg = connectionError.connectionError();
let auth = authentication.auth;
const app = express();
const server = require("http").createServer(app);
const io = require('socket.io')(server)
io.on("connection", socket => {
console.log('NEW USER CONNECTED')
});
app.use(express.json());
app.use(cors({origin: true, credentials: true}));
app.use(express.urlencoded({extended: true}));
app.use(cookieParser());
server.listen(process.env.PORT || port, hostname, () => {
console.log(`Listening to ${hostname}:${port}`)
})
Client Code:
import React, {useState, useEffect, useRef, useCallback, useMemo} from 'react';
import { io } from "socket.io-client";
const ENDPOINT = "http://localhost:8090";
let socket;
export default function Chat(props) {
const [text, setText] = useState('')
const [req, setReq] = useState([]);
const [messages, setMessages] = useState([]);
const [send, setSend] = useState(false);
useEffect(() => {
socket = io(ENDPOINT);
console.log('ini socker', socket.connected)
socket.on("connect", (data) => {
console.log(data)
});
}, []);
....
FIXED CODE
/*since my frontend (client-side) was running on localhost:3000,
all u need to do is just define the cors and put the origin url that
u gonna connect to ur socket instance on Node.Js (server) like this.*/
const io = require('socket.io')(server, {
cors: {
origin: [`http://localhost:3000`],
credentials: true
}
})
Related
I'm trying to make a comment section using socket io in my mern stack app. When I was first developing it it works just fine but after shutting VS code down for a rest I couldn't get it to connect anymore : (((
Here's my server.js
require ('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const cookieParser = require('cookie-parser')
const fileUpload = require('express-fileupload')
const { file } = require('googleapis/build/src/apis/file')
const res = require('express/lib/response')
const path = require('path')
const Comments = require('./models/comment')
const app= express()
app.use(express.json())
app.use(cors())
app.use(cookieParser())
app.use(fileUpload({
useTempFiles: true
}))
const http= require('http').createServer(app)
const io= require('socket.io')(http)
//this doesn't give back anything
io.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
// Socket io
let users = []
io.on('connect', socket => {
console.log(socket.id + ' connected.')
// code for comments
socket.on('disconnect', () => {
console.log(socket.id + ' disconnected.')
//socketCleanup();
socket.socket.reconnect();
users = users.filter(user => user.id!== socket.id)
})
})
and here's my GlobalState.js
import React, {createContext, useState, useEffect} from 'react'
import BooksAPI from './api/BooksAPI'
import GenresAPI from './api/GenresAPI'
import UserAPI from './api/UserAPI'
import axios from 'axios'
import io from 'socket.io-client'
export const GlobalState = createContext()
export const DataProvider = ({children})=>{
const[socket, setSocket] = useState(null)
useEffect(() =>{
const socket = io()
setSocket(socket)
return ()=> socket.close()
},[])
const state={
socket
}
return (
<GlobalState.Provider value={state}>
{children}
</GlobalState.Provider>
)
}
I can't find any solution on the internet that works and I don't even know why it's not connecting : ((( please help.
I'm following this tutorial: https://www.youtube.com/watch?v=tBr-PybP_9c
Locally, the app works fine - I can open up some windows and have them talk to each other. However, when I try to deploy the app to Heroku, the clients no longer connect to the server.
Server-side:
const express = require('express');
const cors = require('cors');
const socket = require('socket.io');
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });
const app = express();
app.use(cors());
const port = process.env.PORT || 8080;
const server = app.listen(port, () => {
console.log(`App running on port ${port}`);
});
const http = require('http').Server(app);
const io = socket(http, {
pingInterval: 100,
pingTimeout: 500,
cors: {
origin: '*',
},
});
io.listen(server);
io.on('connection', (socket) => {
const id = socket.handshake.query.id;
socket.join(id);
console.log(`A user has connected with ID ${id}`);
});
I deployed the server to a Heroku dyne, and it built successfully. The client is a separate dyne:
import React, { useContext, useEffect, useState } from 'react';
import io from 'socket.io-client';
const SocketContext = React.createContext();
export function useSocket() {
return useContext(SocketContext);
}
export function SocketProvider({ id, children }) {
const [socket, setSocket] = useState();
useEffect(() => {
// const newSocket = io('https://my-heroku-app.herokuapp.com:48600', {
const newSocket = io('http://localhost:8080', {
query: { id },
});
setSocket(newSocket);
return () => newSocket.close();
}, [id]);
return (
<SocketContext.Provider value={socket}>{children}</SocketContext.Provider>
);
}
This also built successfully. Obviously, localhost:8080 doesn't work when deployed to Heroku - I tried using 'https://my-heroku-app.herokuapp.com:48600' (the server application's name plus the port where it's running on Heroku), and that doesn't work either. The console.log never occurs on the server side when I do heroku logs --tail.
Is there a better way to do this? Can I put these into the same app, so I only have to deploy one project?
I'm working on a project that involves an application built with Electron that interfaces with an express server, running on Localhost or the home network.
Problem right now is, I'm having trouble getting the server to acknowledge any requests from the application.
Here is my front end logic in the electron application:
let ipAddress;
let port;
let requestAddress;
function connect(){
const ipField = document.getElementById("nu-ip").value;
const portField = document.getElementById("nu-port").value;
port = portField;
if (ipField === "") {
ipAddress = 'localhost';
} else {
ipAddress = ipField;
}
port = portField;
if(port === ""){
requestAddress = `http://$(ipAddress)`;
} else {
requestAddress = `http://${ipAddress}:${port}`;
};
alert(requestAddress);
const request = newXMLHttpRequest();
alert(requestAddress);
request.open("GET",`${requestAddress}/connect`).send();
request.onReadyStateChange = (res) => {
alert(res);
}
}
function startup() {
console.log('Hey where does this show up?')
const NuToggle = document.getElementById("NuHelper-enable");
const NuTools = document.getElementById("Nu-tools");
const connectButton = document.getElementById("connect-button");
NuToggle.addEventListener("change", (event) => {
if(event.target.value === 'enable'){
//alert("NuHelper has been enabled");
NuTools.style.display='block';
connectButton.addEventListener('click', connect);
}
})
}
window.onload = startup;
And here is my server:
//require in our basic dependencies
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const errorHandler = require('errorhandler');
const cors = require('cors');
const PORT = 80;
const app = express();
app.use(morgan('dev'));
app.use(bodyParser);
app.use(errorHandler);
app.use(cors());
app.get('/connect',(req, res, next) => {
res.sendStatus(200);
})
app.listen(PORT, () => {
console.log(`Nu is listening on PORT ${PORT}`);
})
I put 80 into the PORT input and it'll alert "http://localhost:80", but it'll get no response at all from the server, and my logging middleware won't acknowledge that it received any request at all, which makes me think that I'm sending the request to the wrong address. Thanks in advance to anyone who understands how to solve this!
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
This is my Server program
const express = require('express')
const socketio = require('socket.io')
const http = require('http')
const cors = require('cors')
const PORT = process.env.PORT || '5000'
const router = require('./router')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
app.use(cors())
app.use(router)
io.on('connection', socket => {
console.log('User has connected.')
socket.on('join', ({name,room}) => {
console.log(name,room)
})
socket.on('disconnect', () => {
console.log("User has disconnected.")
})
})
server.listen(PORT, () => console.log(`Server running on port ${PORT}`))
and this is my Client side program
import React, { useState, useEffect } from "react"
import queryString from 'query-string'
import io from 'socket.io-client'
let socket
const Chat = ({ location }) => {
// eslint-disable-next-line
const [name, setName] = useState('')
// eslint-disable-next-line
const [room, setRoom] = useState('')
const ENDPOINT = 'localhost:5000'
useEffect(() => {
const { name, room } = queryString.parse(location.search);
socket = io(ENDPOINT)
setRoom(room)
setName(name)
socket.emit('join', {name, room})
}, [ENDPOINT, location.search])
return (
<div className='chat'>
<h1>Test</h1>
</div>
)
}
export default Chat
There's no error in the code, the react app seems to working fine , but I couldn't get the connection establishment .
I don't get the Connected console log or Client Connected console log and I don't know why!