Socket.io and express ERR_CONNECTION_REFUSED - javascript

I am getting the error :ERR_CONNECTION_REFUSED. Send button doesn't work. There is also no welcome message displayed at the start for the newly joined user. I tried to solve it by changing ports to localhost. I've seen similar threads in this forum. No solutions help. What are the possible solutions to this problem? Is it related to false endpoint address?
Screenshot
import React, { useState, useEffect } from "react";
import queryString from 'query-string';
import io from "socket.io-client";
import Messages from '../Messages/Messages';
import InfoBar from '../InfoBar/InfoBar';
import Input from '../Input/Input';
import './Chat.css';
let socket;
const Chat = ({ location }) => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const [users, setUsers] = useState('');
const [message, setMessage] = useState('');
const [messages, setMessages] = 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 }, (error) => {
if(error) {
alert(error);
}
});
}, [ENDPOINT, location.search]);
useEffect(() => {
socket.on('message', message => {
setMessages(messages => [ ...messages, message ]);
});
socket.on("roomData", ({ users }) => {
setUsers(users);
});
}, []);
const sendMessage = (event) => {
event.preventDefault();
if(message) {
socket.emit('sendMessage', message, () => setMessage(''));
}
}
return (
<div className="outerContainer">
<div className="container">
<InfoBar room={room} />
<Messages messages={messages} name={name} />
<Input message={message} setMessage={setMessage} sendMessage={sendMessage} />
</div>
</div>
);
}
export default Chat;
Server part
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const cors = require('cors');
const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(cors());
app.use(router);
io.on('connect', (socket) => {
socket.on('join', ({ name, room }, callback) => {
const { error, user } = addUser({ id: socket.id, name, room });
if(error) return callback(error);
socket.join(user.room);
socket.emit('message', { user: 'admin', text: `${user.name}, welcome to room ${user.room}.`});
socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name} has joined!` });
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room) });
callback();
});
socket.on('sendMessage', (message, callback) => {
const user = getUser(socket.id);
io.to(user.room).emit('message', { user: user.name, text: message });
callback();
});
socket.on('disconnect', () => {
const user = removeUser(socket.id);
if(user) {
io.to(user.room).emit('message', { user: 'Admin', text: `${user.name} has left.` });
io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room)});
}
})
});
server.listen(process.env.PORT || 5000, () => console.log(`Server has started.`));

Related

My Heroku Deployed MERN app can POST to MongoDB Atlas but not GET

As the title states, I have deployed onto Heroku and my MongoDB backend is hosted on MongoDB Atlas. I can POST data to my backend (I see it in my Collections in MongoDB Atlas) but cannot GET any of the information (I get a 500 Internal Server Error thrown). This works locally and as the POSTs go through, I know it's not a URI issue. I'm just a little stumped.
My Component calling the db.
import axios from "axios";
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import GoogleMapReact from "google-map-react";
import "../styles/Details.css";
import Brewery from "../components/Brewery";
import Reviews from "../components/Reviews";
const Details = () => {
let [brewery, setBrewery] = useState([]);
let [reviews, setReviews] = useState([]);
const [toggle, setToggle] = useState(false);
const [rerend, setRerend] = useState(false);
let { name, id, lati, long } = useParams();
const API_KEY = process.env.REACT_APP_GOOGLE_MAP_API_KEY;
let longi = parseFloat(long);
let ltit = parseFloat(lati);
let address =
brewery.street +
" " +
brewery.city +
", " +
brewery.state +
" " +
brewery.postal_code;
const defaultProps = {
center: {
lat: ltit,
lng: longi,
},
zoom: 11,
};
if (brewery.street === null) {
address = "Not Available";
}
useEffect(() => {
// Get info from OpenBrewery API
const getBrewery = async () => {
let select = await axios.get(
`https://api.openbrewerydb.org/breweries?by_name=${name}`
);
setBrewery(select.data[0]);
};
getBrewery();
// Pull reviews from db
const getReviews = async () => {
let rev = await axios.get(`/api/review/${id}`);
setReviews(rev.data);
};
getReviews();
}, [toggle, rerend]);
console.log(reviews);
return lati === "null" ? (
<div>
<div className={`main-bg-color details-container-no-map`}>
<h1 className="details-item-no-map">{brewery.name}</h1>
<h3 className="details-item-no-map">{address}</h3>
<h3 className="details-item-no-map">{brewery.phone}</h3>
<h3 className="details-item-no-map">{brewery.website_url}</h3>
<div>
<Reviews
brewery={brewery}
reviews={reviews}
toggle={toggle}
setToggle={setToggle}
rerend={rerend}
setRerend={setRerend}
/>
</div>
</div>
</div>
) : (
<div>
<div className={`main-bg-color details-container`}>
<div>
<h1 className="details-item">{brewery.name}</h1>
<h3 className="details-item">{address}</h3>
<h3 className="details-item">{brewery.phone}</h3>
<h3 className="details-item">{brewery.website_url}</h3>
</div>
<div className={`map-container`}>
<GoogleMapReact
options={{
gestureHandling: "greedy",
}}
bootstrapURLKeys={{
key: `${API_KEY}`,
}}
defaultCenter={defaultProps.center}
defaultZoom={defaultProps.zoom}
>
<Brewery
lat={defaultProps.center.lat}
lng={defaultProps.center.lng}
name={`${brewery.name}`}
/>
</GoogleMapReact>
</div>
</div>
<div>
<Reviews
className="reviews"
brewery={brewery}
reviews={reviews}
toggle={toggle}
setToggle={setToggle}
rerend={rerend}
setRerend={setRerend}
/>
</div>
</div>
);
};
export default Details;
My db index.js
const mongoose = require("mongoose")
require('dotenv').config()
let dbUrl = process.env.NODE_ENV === 'production' ? process.env.MONGODB_URI : 'mongodb://127.0.0.1:27017/atl-brew-db'
mongoose
.connect(dbUrl)
.then(() => {
console.log("Connected to MongoDB")
})
.catch((e) => {
console.error("Connection error", e.message)
})
mongoose.set("debug", true)
const db = mongoose.connection;
module.exports = db
My server.js
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
const db = require('./db')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use(express.static(`${__dirname}/client/build`))
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
})
}
const reviewController = require('./controllers/reviewController')
const { Review } = require('./models')
app.get('/api/review/:id', reviewController.getReview)
app.post('/api/review', reviewController.postReview)
app.put('/api/review/:id', reviewController.updateReview)
app.delete('/api/review/:id', reviewController.deleteReview)
app.get('/api/review', reviewController.getAllReviews)
app.get('/api/review/single/:id', reviewController.getReviewById)
app.listen(port, () => console.log(`Listening on port ${port}`))
My Controller
const {Review} = require("../models")
const getReview = async (req, res) => {
let result = await Review.find( {brewId: `${req.params.id}`})
res.json(result)
}
const postReview = async (req, res) => {
let review = req.body
// console.log(review, "This is the console log")
Review.create(review)
res.json(review)
}
const deleteReview = async (req, res) => {
await Review.findByIdAndDelete(req.params.id)
console.log(`Review deleted. ID: ${req.params.id}`)
res.send("Delete affirmed")
}
const updateReview = async (req, res) => {
await Review.findByIdAndUpdate(req.params.id, req.body, {new: true})
res.send("Review Updated")
}
const getAllReviews = async (req, res) => {
let result = await Review.find({})
res.json(result)
}
const getReviewById = async (req, res) => {
let result = await Review.findById(req.params.id)
res.json(result)
}
module.exports ={
getReview,
postReview,
deleteReview,
updateReview,
getAllReviews,
getReviewById,
}
Let me know if you need anything else but any help would be greatly appreciated. I'm ramming my head up against this one.

curl works from within the private network, but Axios requests not working on browser

I have a Red Hat Enterpise Linux 9 server hosted at a data center, which has an Apache web server and a MySQL installation. MySQL listens on 3306, and Apache on 80 (defaults).
I'm new to React and Express, and I'm testing a client-server app. I built the client side with create-react-app, and this is the code for App.js
App.js
import "./App.css";
import { useState } from "react";
import Axios from "axios";
function App() {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const [country, setCountry] = useState("");
const [position, setPosition] = useState("");
const [wage, setWage] = useState(0);
const [newWage, setNewWage] = useState(0);
const [employeeList, setEmployeeList] = useState([]);
const addEmployee = () => {
Axios.post("http://1.2.3.4:3001/create", {
name: name,
age: age,
country: country,
position: position,
wage: wage,
}).then(() => {
setEmployeeList([
...employeeList,
{
name: name,
age: age,
country: country,
position: position,
wage: wage,
},
]);
});
};
const getEmployees = () => {
Axios.get("http://1.2.3.4:3001/employees").then((response) => {
setEmployeeList(response.data);
console.log("retrieving the list");
console.log(employeeList);
});
};
getEmployees();
const updateEmployeeWage = (id) => {
Axios.put("http://1.2.3.4:3001/update", { wage: newWage, id: id }).then(
(response) => {
setEmployeeList(
employeeList.map((val) => {
return val.id == id
? {
id: val.id,
name: val.name,
country: val.country,
age: val.age,
position: val.position,
wage: newWage,
}
: val;
})
);
}
);
};
const deleteEmployee = (id) => {
Axios.delete(`http://1.2.3.4:3001/delete/${id}`).then((response) => {
setEmployeeList(
employeeList.filter((val) => {
return val.id != id;
})
);
});
};
return (
<div className="App">
<div className="information">
<label>Name:</label>
<input
type="text"
onChange={(event) => {
setName(event.target.value);
}}
/>
<label>Age:</label>
<input
type="number"
onChange={(event) => {
setAge(event.target.value);
}}
/>
<label>Country:</label>
<input
type="text"
onChange={(event) => {
setCountry(event.target.value);
}}
/>
<label>Position:</label>
<input
type="text"
onChange={(event) => {
setPosition(event.target.value);
}}
/>
<label>Wage (year):</label>
<input
type="number"
onChange={(event) => {
setWage(event.target.value);
}}
/>
<button onClick={addEmployee}>Add Employee</button>
</div>
<div className="employees">
<button onClick={getEmployees}>Show Employees</button>
{employeeList.map((val, key) => {
return (
<div className="employee">
<div>
<h3>Name: {val.name}</h3>
<h3>Age: {val.age}</h3>
<h3>Country: {val.country}</h3>
<h3>Position: {val.position}</h3>
<h3>Wage: {val.wage}</h3>
</div>
<div>
<input
type="text"
placeholder="2000..."
onChange={(event) => {
setNewWage(event.target.value);
}}
/>
<button
onClick={() => {
updateEmployeeWage(val.id);
}}
>
{" "}
Update
</button>
<button
onClick={() => {
deleteEmployee(val.id);
}}
>
Delete
</button>
</div>
</div>
);
})}
</div>
</div>
);
}
export default App;
The server is supposed to run on port 3001 of the same machine. The code for the server's index.js is below.
index.js for server
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user: "apphost",
host: "0.0.0.0",
password: "password",
database: "employeeSystem",
insecureAuth: 'true'
});
app.get('/home', (req, res) => {
res.send("HELLO THERE\n");
});
app.post("/create", (req, res) => {
const name = req.body.name;
const age = req.body.age;
const country = req.body.country;
const position = req.body.position;
const wage = req.body.wage;
db.query(
"INSERT INTO employees (name, age, country, position, wage) VALUES (?,?,?,?,?)",
[name, age, country, position, wage],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
});
app.get("/employees", (req, res) => {
db.query("SELECT * FROM employees", (err, result) => {
if (err) {
console.log('server index.js problem')
console.log(err);
} else {
res.send(result);
}
});
});
app.put("/update", (req, res) => {
const id = req.body.id;
const wage = req.body.wage;
db.query(
"UPDATE employees SET wage = ? WHERE id = ?",
[wage, id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
app.delete("/delete/:id", (req, res) => {
const id = req.params.id;
db.query("DELETE FROM employees WHERE id = ?", id, (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});
app.listen(3001, () => {
console.log("Server running on port 3001.");
});
After running the server with node index.js, when I run curl http://1.2.3.4:3001/employees from a machine on the same physical network, I get a JSON output of the data in the MySQL database as expected. From my Windows CMD, a browser on my Windows machine, or from my phone, the request times out.
Keep in mind that I'm SSH-ing to the linux VM, while on a VPN provided by the data center.
This is the error I get on chrome:
Uncaught (in promise) M {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
Not sure what the issue is. Tried a lot of solutions from all over the internet, but nothing seems to work.
If any more information is needed, feel free to ask. I'll do anything to get this issue fixed and understand what I'm doing wrong.
Thanks in advance!

Socket io delay one event

I have connected socket io to Webhook and it succeeds. It can get information and can express But I'm stuck with one problem. When the desired value is displayed on the client-side, the response is delayed. For example, when the server-side detects an event will show on console.log(); But it won't show on the client-side. But when the server-side detects the event again (second time) The value saved the first time is sent to the client-side, and if the server detects the event again (third time) The second event value is sent to the client-side, which means it will delay the event one time. How can I fix this incident?
// Server
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io', {
transports: ['websocket', 'polling']
})(http, {
cors: {
origin:'*'
}
});
const bodyParser = require("body-parser");
PORT = 8080;
io.on('connection', socket => {
app.use(bodyParser.json());
app.post('/api', (req, res) => {
let x = req.body[0];
let dates = x.created_date;
let name = x.name;
let watchlist = x.watchlist[Object];
if (watchlist == "Matched"){
console.log("Date :", dates)
console.log("Name :", name)
io.emit('FromAPI', dates, name);
}
else {
console.log("Unmatch")
}
res.status(200).end("Successfully");
});
console.log('Socket connected');
socket.on('disconnect', () => { console.log('Socket disconnected')});
});
http.listen(PORT, () => {
console.log(`Server : http://localhost: ${PORT}`);
});
// Client
import { useEffect, useState } from 'react';
import io from 'socket.io-client';
const socket = io("http://localhost:8080", { transports: ['websocket', 'polling'] });
export default function App() {
const [date, setDate] = useState('');
const [name, setName] = useState('');
const [hook_event, setHook_event] = useState([
{ "date": date, "name": name},
{ "date": date, "name": name}
]);
useEffect(() => {
socket.on('FromAPI', (date, name) => {
setDate(date);
setName(name);
hook_event.unshift({"date": date, "name": name});
hook_event.pop();
})
}, [];
return (
<>
<p>Date : {hook_event[0].date} and {hook_event[0].name}</p>
<p>Date : {hook_event[1].date} and {hook_event[1].name}</p>
</>
);
};
I think I found the problem.
const [countState, setCountState] = useState()
useEffect(() => {
socket.on('FromAPI', (date, name) => {
setDate(date);
setName(name);
hook_event.unshift({"date": date, "name": name});
hook_event.pop();
setCountState(hook_event[0])
})
}, [setCountState]; // update setCountState

no response socket.io with reactjs

two info: [HMR] Waiting for update signal from WDS...
Download the React DevTools for a better development experience: fb.me/react-devtools
error: http://127.0.0.1:4001/socket.io/?EIO=3&transport=polling&t=N4qdmGu
Failed to load resource: net::ERR_CONNECTION_REFUSED what should be done to make this work?
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001;
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server);
let interval;
io.on("connection", socket => {
console.log("New client connected");
if (interval) {
clearInterval(interval);
}
interval = setInterval(() => getApiAndEmit(socket), 10000);
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
const getApiAndEmit = async socket => {
try {
const res = await axios.get(
"https://api.darksky.net/forecast/db057094f57ede5e1f8d33d5e528e4b3/30.9871097,34.9408864"
);
let temp = (((res.data.currently.temperature - 32) * 5) / 9).toFixed(2);
socket.emit("FromAPI", temp);
} catch (error) {
console.error(`Error: ${error.code}`);
}
};
server.listen(port, () => console.log(`Wee wee i'm on port ${port}`));
than
import React, { Component } from "react";
import socketIOClient from "socket.io-client";
class App extends Component {
constructor() {
super();
this.state = {
response: false,
endpoint: "http://127.0.0.1:4001"
};
}
componentDidMount() {
const socket = socketIOClient(this.state.endpoint);
socket.on("FromAPI", data => this.setState({ response: data }));
}
render() {
const { response } = this.state;
return (
<div style={{ textAlign: "center" }}>
{
response ?
(<p>The temperature is {response} degrees</p>)
:
(<p>load load...</p>)
}
</div>
);
}
}
export default App;
You have to first connect to the socket server on the client side so for that add this
socket.on('connect', function(){});
before your event listener.
socket.on("FromAPI", data => this.setState({ response: data }));

front end react is not sending data to to mongoDB database

THE app is suppose to register the new user and send the new users info to the MongoDB, but when i attempt to register the user it throws an error of 500 internal error. the console says the error is in the user file, the terminal say this is the error, Proxy error: Could not proxy request /api/users from localhost:3000 to https://localhost:5000.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (EPROTO).
I've already tried changing the proxy in the packet.json by giving it a different path and target but its not working. maybe i'm overlooking something. enter code here
import React, { useReducer } from 'react';
import axios from 'axios';
import AuthContext from './authContext';
import authReducer from './authReducer';
import {
REGISTER_SUCCESS,
REGISTER_FAIL,
USER_LOADED,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT,
CLEAR_ERRORS
} from '../types';
const AuthState = props => {
//initial state
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
user: null,
loading: true,
error: null
};
const [ state, dispatch ] = useReducer(authReducer, initialState);
// load user
const loadUser = () => console.log('load user') ;
// register user
const register = async formData => {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
try {
const res = await axios.post('api/users', formData, config);
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
});
} catch (err){
dispatch({
type: REGISTER_FAIL,
payload: err.response.data.msg
});
}
}
// login user
const login = () => console.log('login') ;
//logut
const logout = () => console.log('logout') ;
// clear errors
const clearErrors = () => console.log('clearErrors') ;
return (
<AuthContext.Provider
value= {{
token: state.token,
isAuthenticated: state.isAuthenticated,
loading: state.loading,
user: state.user,
error: state.error,
register,
loadUser,
login,
logout,
clearErrors
}}>
{props.children}
</AuthContext.Provider>
);
};
export default AuthState;
//this is my server.js file with the routes
const express = require('express');
const connectDB = require('./config/db')
//connect MongoDB
connectDB();
const app = express();
//init middleware
app.use(express.json({extended: false}));
app.get('/', (req, res) => res.json({ msg: 'hello welcome'})
);
//define routes
app.use('/api/users', require('./routes/users'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/contacts', require('./routes/contacts'))
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`server is working on ${PORT}`))
// this is mongoDB code
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () =>{
try{ await
mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
});
console.log('mongo connected..')
} catch (err){
console.log(err.message);
process.exit(1)
}
};
module.exports = connectDB;
// this the users file where the console is throwing the 500 internal error.
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const { check, validationResult } = require('express-validator');
const User = require('../models/User')
// This route Post request to api/users,
// description register a user,
// access to public to register an become a user
router.post('/', [
check('name', 'Name is require').not().isEmpty(),
check('email', 'please include email').isEmail(),
check('password', 'enter a password with atleast 6 characters'
).isLength({min: 6})
],
async (req, res) =>{
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({ errors: errors.array()});
}
const { name, email, password } = req.body;
try{
let user = await User.findOne({email});
if(user){
return res.status(400).json({msg: 'user already exist'})
}
user = new User({
name,
email,
password
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// object to send in the token
const payload = {
user: {
id: user.id
}
}
jwt.sign(payload, config.get('jwtSecret'), {
expiresIn: 36000
}, (err, token) => {
if(err) throw err;
res.json({token});
});
} catch (err){
console.log(err.message);
res.status(500).send('server error')
}
});
module.exports = router;
I figure out the problem!!!
I had an unexpected token in my users file that simple colon was interfering with the code

Categories

Resources