NodeJS | working with two protocols in server - javascript

i would like to work with http protocol and websocket on my server, and i will explain:
i have a chat app and i have a login page and chat page.
i would like to use the http protocol on login page and websocket for my chat page.
and if the answer yes, can i do this ?
const express = require('express')
const http = require('http')
const app = express()
const server = http.createServer(app)
const io = socketio(server)
in.on('connection', (req,res) => {
//...
})
app.get('/',(req,res) => {
//...
})
server.listen(port, (req, res) => {
console.log('Server is listen on port ' + port)
})

Related

How can I redirect the user to a custom URL scheme with Express.js and node-fetch?

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://...')

socket io client not connecting to server using ipv4 address

I'm having a problem with testing the connection when I use https://localhost:3000/ it connects successfully but I want to use socket Io client on a different device on android application to be precise I searched it up and turns out localhost wont work I have to connect using ipv4 address well I tried it but didnt work - like this http http://192.168.XX.XX:3000 for example so what is the problem why doesnt it connect please help
server code:
var cors = require("cors");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000 ;
const server = app.listen(port, () => {
console.log(`started on ${port}`);
})
const io = require('socket.io')(server, {
cors: { origin: "*" }
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (message) => {
console.log(message);
io.emit('message', `${socket.id.substr(0,2)} said ${message}` );
});
});
require("dotenv").config();
app.use(express.json());
app.use(cors());
//routes setup
const homeGetRoute = require("./routes/test.js");
app.use("/home", homeGetRoute);
app.use(cors());

Listening for connections with socket.io not working

I'm using this code for my backend:
const express = require('express');
const app = express();
const socketIo = require("socket.io");
const io = socketIo(http);
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
When I run it, it outputs the message confirming it is listening. However, on a connection it does not send any messages to the console. I'm trying to listen for connections to a React app. I have tried using other code snippets for the connection function that also claim to work as I expected, however none that I have tried have worked, including the code in the official tutorial for socket.io.
Please can anyone help?
const express = require('express')
const app = express()
const PORT = 5000
// Get to http://localhost:5000
app.get("/", (request, response) => {
// Send back some data to the client
response.send("Hello world")
})
// Post to http://localhost:5000/getRandom
app.post("/getRandom", (req, res) => {
res.send(Math.random())
})
app.listen(PORT, () => console.log(`Server running on PORT ${PORT}`))
Instead of calling the parameters request and response, people use the short form of req and res
Now start this script and go to http://localhost:5000 and you will see "Hello world" in the HTML body. That's express, simple yet powerful :)

React/NodeJS won't speak via localhost in development

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.

Adding socket.io to an existing Express project (with React on the front)

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/

Categories

Resources