Cannot access Node.JS Backend via localhost - javascript

I'm working to setup a Node backend to feed data and communicate with ReactJS for my frontend. Ultimately I am developing new company software to replace our current Transportation System.
I utilize Amazon EC2 Ubuntu 16.04 - for my own reasons for my business - and I simply cannot get my ReactJS frontend with Socket.IO to communicate with my nodeJS backend with Socket.IO on http://localhost:4000/.
This is my App.js in my react frontend
import React, { Component } from 'react';
import logo from './logo.svg';
import ioClient from 'socket.io-client';
import './App.css';
var socket;
class App extends Component {
constructor() {
super();
this.state = {
endpoint: 'http://localhost:4000/'
};
socket = ioClient(this.state.endpoint);
}
This is my nodeJS index for the backend
const mysql = require('mysql');
const http = require('http');
const express = require('express');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const io = require('socket.io').listen(server);
//app.use(cors());
app.get('/', (req, res) => {
res.send('Server running on port 4000')
});
const sqlCon = mysql.createConnection({
host: 'localhost',
user: 'admin-user',
password: 'admin-pass',
database: 'sample'
});
sqlCon.connect( (err) => {
if (err) throw err;
console.log('Connected!');
});
io.on('connection', (socket) => {
console.log('user connected');
});
server.listen(4000, "localhost", () => {
console.log('Node Server Running on 4000')
});
I can get it to communicate via my actual Public IP address, but not via localhost. I really don't want to expose my backend on my public IP address to communicate with it for all users. This has probably been asked before, but I honestly can't find a clear answer for it anywhere and I've been looking for 3 days now. Node has no problem executing, and like I said if I create the socket.io connection from the public IP, I can get it to communicate and as far as I can tell node has no problem running the rest of the script as it connects to mariaDB no problem.

Related

How to connect front and back end using replit & mongodb?

I made a simple full stack app for a job application using a mern stack. The application requires the app to be deployed on replit. I was able to run my app from my laptop but I am having issue connecting my back end with my front end api calls.
I have not used replit or other online coding platforms much before, so I am not very sure how to. If I run my front end on replit and my back end from my local laptop files, the api calls are working fine. But If I run start both front and back end on replit, the server will start but no API calls will reach it.
Here is the replit link: https://replit.com/#MayurKumar4/In-replit-how-to-connect-to-mongoosemongo-api-endpoints?v=1
Below is the index page of my express app.
The dbURI is currently linked to a mongodb atlas cluster I have set up and is working with some seed data.
port is set to 4000
import express from 'express'
import mongoose from 'mongoose'
import router from './config/routes.js'
import { port, dbURI } from './config/environment.js'
import cors from 'cors'
const app = express()
const startServer = async () => {
try {
// Attempt mongodb connection
await mongoose.connect(dbURI)
console.log('Mongodb connected')
// --Middleware--
// JSON Parser
app.use(express.json())
app.use(cors())
// Logger
app.use((req, _res, next) => {
console.log(`🚨 Request received: ${req.method} - ${req.url}`)
next()
})
// Routes
app.use('/api', router)
// Catch All
app.use((_req, res) => {
return res.status(404).json({ message: 'Route Not Found' })
})
// If mongodb connects successfully
app.listen(port, () => console.log(`🚀 Server listening on port ${port}`))
} catch (err) {
console.log(err)
}
}
startServer()

socket.io client not firing events on socket io server

I have built a backend and wanted to test it with some front-end code but for whatever reason, it is just not firing the events on the server. I dont get the "on connect" event triggered. I already downgrade the backend to a version similar to my testing script but still all the server shows, are logs like this.
[22/Oct/2021:14:06:21 +0000] "GET /socket.io/?EIO=4&transport=polling&t=NoeKlFT&b64=1 HTTP/1.1" 404 149 "-" "node-XMLHttpRequest"
I am using socket io for server and client version 3.1.2
Here is the backend code snippet
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const morgan = require("morgan");
const cors = require("cors");
const config = require("./src/config/general");
const exchangeController = new ExchangeController(io); // I want to pass in the IO obejct to be able to deal with all the event stuff in another file besides the apps entry point file.
Here is the part where I want the IO object to be available and work with the events from there
class ExchangeController {
constructor(io) {
this.io = io;
this.exchangeService = new ExchangeService();
this.router = express.Router();
this.initRoutes();
this.io.on("connection", (socket) => {
console.log("incoming socket connection"); //gets never logged to console when connecting frontend
//do further stuff (deleted for post)
});
});
}
This is the frontend script for testing the connection
//client.js
const io = require('socket.io-client');
const socket = io("mysecreturl") //also tried localhost instead of deployed app url no difference
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
I really tried for way too long now without getting any results. I hope you guys can guide me on the right path again.
Cheers

How to connect to a nodejs socket server?

I am new to node JS and I am trying to create a real time application that consists of a node JS server with socket.io and a unity application that can connect to it
I created the server with the sockets in the below code :
const express = require('express');
const http = require('http');
const app = express();
const port = process.env.PORT || 9000;
const server = http.Server(app);
const io = require('socket.io')(server);
io.on('connection',(socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
app.get('/',(req,res) =>{
res.json({worked : 'worked'});
});
server.listen(port,() => console.log(`Listening on localhost ${port}`));
I can connect to the socket server via the nodejs client files using socket.io-client
<script>
const socket = io('http://localhost:9000');
socket.on('message',(message) => console.log(message));
</script>
But the problem is whenever I try to connect from a different client I don't receive anything in the console.
I tried to use Smart Web Socket client to debug what's happening but whenever I connect (try to)
this happens
Any help would be much appreciated and thanks in advance
So if anyone stumbles in this thread I was able to fix the problem by installing the latest version of socket.io (^3.1.0) and allowing the EIO3 connections

Implement a socket connection in my apollo graphQL express server

I'm running an express based apollo graphQL server using apollo-server-express.
import express from 'express'
import cors from 'cors'
import server from './graphql/schema'
app.use(cors())
server.applyMiddleware({ app, path: '/graphql' })
app.listen(port, async () => {
if (process.env.NODE_ENV !== 'production') {
console.log('Listening on port ' + port)
}
})
export default app
Now I need to connect to some other applications from my client. Therefore he provides me with HL7 data. He told me to 'use a socket to get the HL7 data', which my application can use.
I just don't have a clue how to implement a socket connection at all.
Doing some researches brought me to libraries like socket.io, which should be used like this (for express):
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000)
I don't understand how to implement the io in my existing code shown above.
I never used or implemented a socket connection at all, so I have very big understanding problems with that. Maybe the socket.io library is not the correct thing for my needs.
I do not have any knowlege about HL7 data, I think your another app has been writen by Java.
But, if you want to implement a socket.io server with apollo-server-express, just follow socket.io official document and attach a http server to express app and socket.io, then start your http server.
import express from 'express'
import cors from 'cors'
import GraphQLServer from './graphql/schema'
import socketIO from 'socket.io'
import http from 'http'
let app = express() // You missed this line ?
let httpServer = http.Server()
let io = socketIO(httpServer)
app.use(cors())
GraphQLServer.applyMiddleware({ app, path: '/graphql' })
httpServer.listen(port, async () => { // I don't see your `port`
if (process.env.NODE_ENV !== 'production') {
console.log('Listening on port ' + port)
}
})
io.on('connection', (socket) => {
console.log('A client connected', socket.id)
});
export default app

Nuxt JS with WebSockets

I have a Nuxt App, with one service which needs to be delivered over WebSockets. The Nuxt App Server provides an api service using express.
I have an /api folder in which there are various *.js files, and these are routed to successfully. ie...
const express = require('express');
const app = express();
app.get('/whatever1',(req, res) => console.log('req.url',req.url))
works OK.
However the following, in the same file, will never be reached....
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.ws('/whatever2',(ws,req) => {
console.log('req.url',req.url);
})
Where am I going wrong ?
You're attempting to connect the client to an endpoint on the server where no such endpoint exists. In your client's output, you're receiving an error of:
VM1295:1 WebSocket connection to 'ws://localhost:3000/api/whatever2' failed: Connection closed before receiving a handshake response
because you haven't defined a route of /api/whatever2. Your code above routes to:
ws://localhost:3000/whatever2
instead of ws://localhost:3000/api/whatever2
EDIT:
Here's test code that worked for me:
const express = require('express');
var app = express();
const expressWS = require('express-ws')(app);
expressWS.getWss().on('connection', function (ws) {
console.log('connection open');
});
app.ws('/whatever', (ws, res) => {
console.log('socket', ws);
});
app.listen(3000, () => console.log('listening on 3000...'));

Categories