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 when it calls
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.
This is the error I keep receiving in my Chrome console.
polling-xhr.js:271 GET http://localhost:4000/socket.io/?EIO=3&transport=polling&t=MvBS0bE net::ERR_CONNECTION_REFUSED
polling-xhr.js:271 GET http://localhost:4000/socket.io/?EIO=3&transport=polling&t=MvBS3H8 net::ERR_CONNECTION_REFUSED
I'm running React via npm start for the time being, so my localhost:3000 is being reverse proxied to nginx for my React frontend to be visible on my public EC2 IP via port 80.
Any help is appreciated!
It may be a cross origin request issue. Have you tried to enable CORS on your app. You can also use proxy in your react app package.json if you do not want to enable cors on your app.
In your react app package.json you can add
"proxy":"http://localhost:4000"
It's probably because the port you are using isn't available in the server-side when it's running.
Use the server-side port like this,
var port = process.env.PORT || 3000;
server.listen(port, "localhost", () => {
console.log('Node Server Running on 4000')
});
and on the client-side just connect to the app URL, like,
this.state = {
endpoint: '/'
};
socket = ioClient(this.state.endpoint);
Just clean up your server a bit. Take this guy run him from whatever terminal or ide you use to get your server going.
let startTime = Date.now();
const express = require('express');
const bodyParser = require('body-parser');
const compression = require('compression');
var cors = require('cors');
const app = express();
app.use(compression());
app.use(bodyParser.json({ limit: '32mb' }));
app.use(bodyParser.urlencoded({ limit: '32mb', extended: false }));
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.use(cors({ origin: 'null' }));
const request = require('request');
const port = 4000;
let pm2InstanceNumber = parseInt(process.env.NODE_APP_INSTANCE) || 0;
http.listen(port + pm2InstanceNumber, err => {
if (err) {
console.error(err);
}
console.log('Listening http://localhost:%d in %s mode', port + pm2InstanceNumber);
console.log('Time to server start: ' + (Date.now() - startTime) / 1000.0 + ' seconds');
setTimeout(() => {
try {
process.send('ready');
} catch (e) {}
}, 2000);
app.get('/', (req, res) => {
res.send('Server running on port 4000')
});
});
or just run node filename.js to serve this guy up.
Related
Sorry if my usage of server-related words is wrong, I'm new to this. I have two Express.js servers one on port 3000 and one on port 8000. The browser renders two different HTML files on these two ports. First I start the server on port 8000. As soon as I start the server on port 3000, I want to redirect the user viewing the site on port 8000 to a custom URL scheme to open an installed app (using "example://"). At the moment I console.log "received" on port 8000 as soon as the other server starts. How can I redirect the user to the URL "example://" so that the app opens?
This is my code for server one (port 3000):
import express, { response } from "express";
import fetch from "node-fetch";
import * as path from 'path';
import { fileURLToPath } from "url";
const touchpointApp = express();
const port = 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
touchpointApp.get('/', (req, res) => {
res.sendFile('/index.html', { root: __dirname });
});
touchpointApp.listen(port, () => {
console.log('Running on Port 3000');
fetch("http://192.168.2.127:8000/launch").then(res => {console.log("Success")});
})
And this is my code for server two (port 8000):
const { response } = require('express');
const express = require('express');
const open = require('open');
const router = express.Router();
const path = require('path');
const smartMirror = express();
router.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
smartMirror.use('/', router);
smartMirror.listen(process.env.port || 8000);
console.log('Running on Port 8000');
smartMirror.get("/launch", (req, res) => {
console.log("Received");
res.status(200);
})
The code is currently Frankenstein's monster because of the previous tests. I'm using NodeJS to start the servers.
This is my understanding of your intent:
User in browser visits http://somehost:8000/someUrl and gets a page
You start server on port 3000, the 8000 server somehow detects this
Subsequent requests to http://somehost:8000/someUrl are now redirected to http://somehost:3000/differentUrl and hence the user is now navigating among pages in the 3000 server. Note that the 8000 server is telling the browser: "don't look here, go to the 3000 server for your answer".
If that is your intent then you can send a redirect by
smartMirror.get("/launch", (req, res) => {
res.redirect("http://somehost:3000/differentUrl");
})
So you might have code such as
smartMirror.get("/launch", (req, res) => {
// assuming that you can figure out that the 3000 server is running
if ( the3000ServerIsRunning ) {
let originalURL = req.originalUrl;
let redirectedURL = // code here to figure out the new URL
res.redirect("http://somehost:3000" + redirectedURL);
else {
// send a local respons
}
})
I think you can do it with the location http response header.
res.location('example://...')
hi as you know public server is down so i tried to host my on peer server
i already had a nodejs/express server up for chat ... so i tried to integrate peer server on my chat server
here is simplified version of my code
const env = require('dotenv').config({ path: '.env' })
const express = require('express');
const { ExpressPeerServer } = require('peer');
const fs = require('fs');
const app = express();
const https = require('https');
const http = require('http');
let server ;
if(env.parsed.PROTOCOL === 'https')
{
// server = create https server
}
else
{
server = http.createServer( app);
}
const { Server } = require("socket.io");
const io = new Server(server);
const peerServer = ExpressPeerServer(server, {
debug: true
});
app.use('/peerjs', peerServer);
io.sockets.on('connection', function(socket) {
console.log(`# connection | socket -> ${socket.id} |`);
});
var PORT = env.parsed.PORT || 8080
server.listen(PORT, () => {
console.log(`listining to port ${PORT} `);
});
the problem is after adding peer server to my code i cant establish any socket.io connection to the server ... i get no errors in the server i just get the client side error
WebSocket connection to 'ws://localhost:8080/socket.io/?EIO=4&transport=websocket' failed: Invalid frame header
server is up and working , if i type localhost:8080 in the browser i will get the response
if i remove peer server code it would work fine
i can move peer server to separate code and run on a different port but i prefer to keep it in this code
any idea why this happening ?
According to this issue, it's not possible to run socket.io and a PeerJS server on the same Express(/http(s) server) instance.
You should be able to start a separate PeerJS server from the same code file, as explained here:
const { PeerServer } = require('peer');
const peerServer = PeerServer({ port: 9000, path: '/myapp' });
I am trying to host my website, written with ExpressJS, using namecheap's cPanel, along with cloudflare, but can't seem to figure out how to deploy it. There isn't an option for a Node.js application so I resorted to using my cPanel's terminal to host it. Here's my basic ExpressJS code that I used for testing:
const express = require('express')
const https = require("https")
const fs = require("fs")
const app = express()
const cert = fs.readFileSync("./cert.crt")
const ca = fs.readFileSync("./ca.ca-bundle")
const key = fs.readFileSync("./private.key")
let options = {
cert: cert,
ca: ca,
key: key
}
let server = https.createServer(options, app)
app.get('/test', (req, res) => {
res.send('Hello World!')
})
server.listen(8080, 'shared ip', () => { console.log("Hosting!") });
Whenever I go to mydomain.com the index.html file gets served like normal, but when I go to mydomain.com/test I get a 404 not found. When looking at the GET request my site seems to be getting my server's IP with port 443 instead of 8080. Then when I go to mydomain.com:8080/test I get ERR_SSL_PROTOCOL_ERROR. I'm not totally sure how to fix this.
Port 443 is the standard TCP port that is used for website by default
try changing to server.listen(process.env.PORT || 80, () => { console.log("Hosting!") });
or server.listen(443, 'shared ip', () => { console.log("Hosting!") });
I am using Firebase Functions as the host for my MERN web app backend.
When I connect to MongoDB locally, it works and can run operations with the database. However, when I deployed to firebase functions, it failed to even connect to the database.
Code:
index.js
const functions = require('firebase-functions');
const server = require('./server.js');
exports.api = functions.runWith({ memory: "2GB", timeoutSeconds: 120 }).https.onRequest(server);
Part of server.js
const express = require("express");
const dotenv = require("dotenv");
const colors = require("colors");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const bodyParser = require("body-parser");
const routes = require("./routes/routes.js");
const mongooseMethods = require("./database.js");
dotenv.config({ path: "./config/config.env" });
mongooseMethods.connectDB(process.env.MONGO_URL);
const PORT = process.env.PORT || 8080;
// set up app
const app = express();
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
app.use(cors({ origin: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));
app.use("/api", routes); // /api routes
module.exports = app;
routes.js
const express = require("express");
const app = express.Router();
const testingApi = require('../controller/testing.js');
const authApi = require('../controller/auth.js');
// testing
app.get('/testing', testingApi.testing);
// user authentication
app.post('/user/register', authApi.createUser);
module.exports = app;
api/testing/ also works
database.js
const mongoose = require("mongoose");
const mongooseMethods = {
connectDB: async (url) => {
try {
console.log("Connecting to MongoDB")
const connection = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(`MongoDB Connected: ${connection.connection.host}`.cyan.bold);
return connection;
} catch (error) {
console.log(`Error: ${error.message}, Exiting`.red.bold);
process.exit(1);
}
}
}
module.exports = mongooseMethods;
auth.js
const User = require('../model/user.model.js');
const bcrypt = require("bcryptjs");
let authenticationApi = {
createUser: async (req, res) => {
try {
console.log("Creating");
let newUser = new User({
...req.body
})
let result = await newUser.save();
return res.status(200).json({ result: result });
} catch (error) {
return res.status(400);
}
}
}
module.exports = authenticationApi;
The error I received when sending request to firebase is
2020-02-27T02:34:46.334044912Z D api: Function execution took 30970 ms, finished with status: 'connection error'
Yet it runs perfectly fine in local. I also don't see the console log "connected to MongoDB". I'm guessing that the problem occurs in database.js that it failed to connect to mongo at the first place yet I don't know how to solve.
I am using the paid plan in Firebase and the outbound networking should be fine.
p.s. this is my first time posting here. thanks for your time and I apologize in advance if i'm breaking any rules.
Listening on a port is not a valid operation in cloud functions:
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
Cloud Functions listens for you, using the URL that it was assigned, then delivers the request to your code. When you pass your express app to onRequest(), that's all wired up for you.
I suggest starting with a stripped down, simplified version of an app just to gain experience about how things work, then add in more as you get comfortable.
The reason for this to happen is that the architecture of Firebase Functions is not an actual server, but a serverless lambda-like endpoint. Since it cannot establish a lasting connection to the database, that it has to make a connection every time it received a request, the database sees this as spam and shut down further connection request from Firebase.
Therefore, you simply cannot host a complete express app with intended lasting connection in Firebase Functions.
More on that in this article
I have an existing project written in Express, where I've made a messaging system. Everything was working on POST/GET methods (to send and receive the messages).
I wanted to make them appear in real time, so I installed socket.io both on the client and server side. In my server.js I added these lines:
const http = require("http");
const io = require("socket.io");
const server = http.createServer();
const socket = io.listen(server);
and changed my app.listen(...) into server.listen(...).
Added also:
socket.on("connection", socket => {
console.log("New client connected");
socket.on('test', (test) => {
console.log('test-test')
});
socket.emit('hello', {hello:'hello!'});
socket.on("disconnect", () => console.log("Client disconnected"));
});
On the front part I put such code in the componentDidMount method:
const socket = socketIOClient();
socket.emit('test', {test:'test!'})
socket.on('hello', () => {
console.log('aaa')
})
Now I got 2 problems. Although the console.log() works correctly, I get an error on the React app:
WebSocket connection to 'ws://localhost:3000/sockjs-node/039/lmrt05dl/websocket' failed: WebSocket is closed before the connection is established.
Is that normal?
Also, when I change app.listen(...) into server.listen(...) in the server.js file, my routing stops working. All the POST and GET methods don't work, because the server is responding endlessly. Is that possible to use the socket.io just on a specific method in a specific routing file?
I keep my routes that way: app.use('/api/user', user); where user is a router file.
UPDATE:
full server.js require:
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const bodyparser = require('body-parser');
const passport = require('passport');
const user = require('./routes/api/v1/User');
const company = require('./routes/api/v1/Company');
const http = require("http");
const io = require("socket.io");
const app = express();
dotenv.config();
app.use(passport.initialize());
require('./config/seed');
require('./config/passport')(passport);
const server = http.createServer();
const socket = io.listen(server);
You're not initializing server properly. Try making the following change
// const server = http.createServer();
const server = http.createServer(app);
and make sure you listen on server and not io
server.listen(PORT_GOES_HERE)
[UPDATE]
Working Example:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// WARNING: app.listen(80) will NOT work here!
// DO STUFF WITH EXPRESS SERVER
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
For more details check this: https://socket.io/docs/