Node.JS JavaScript PeerJS ReferenceError: navigator is not defined - javascript

I'm trying to build a simple peer to peer image sharing demo app using Node.JS and PeerJS.
But when I try to run the app, I get an error ReferenceError: navigator is not defined.
This is a node.js backend app so I don't get why PeerJS is requesting to identify the navigator.
Could you please help me spot the problem?
Thanks in advance!
app.js
const express = require('express');
const fs = require('fs');
const { resolve } = require('path');
const Peer = require('peerjs');
const app = express();
const port = 9500;
const sender = new Peer('sender', {
host: 'localhost',
port: port,
path: '/'
});
const receiver = new Peer('receiver', {
host: 'localhost',
port: port,
path: '/'
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.get('/send', (req, res) => {
...
...
let image = readDataset();
const conn = sender.connect('receiver');
conn.on('open',()=> {
conn.send({
photo: image,
});
res.status(200).send("Image sent.");
});
});
app.get('/receive', (req, res) => {
receiver.on('connection', conn => {
conn.on('data', data => {
...
...
res.status(200).send("Image received and saved.");
});
});
});
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});

Related

Express importing app from server.js is giving me an error

I have created an express server in my server.js file, and I export app from it.
//server.js
require("dotenv").config();
const express = require("express");
const app = express();
const connectToDb = require("./connectToDb")
connectToDb().catch(console.dir)
app.use((req, res) => {
res.status(404).send("unable to find");
});
module.exports = app
I import app from server.js in the connectToDb.js file
//connectToDb.js
const app = require("./server")
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const port = process.env.PORT || 3000;
const connectToDb = async () =>{
try {
await client.connect();
console.log("Connected correctly to server");
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
} catch (err) {
console.log(err.stack);
} finally {
await client.close();
console.log("hello")
}
}
module.exports = connectToDb
It connects succesfully to the database, but when it reaches app.listen it gives me this error: TypeError: app.listen is not a function. I don't know why it gives me an error because I have exported app. What am I doing wrong?
That's because you have a cyclic dependency. The two files import each other, and inside server.js you make a call immediately on load. In the moment you call connectToDb inside of server.js, the server.js file has not fully executed yet and hence the module export has not yet happened. Either way it's something you should try to avoid (cyclic dependencies).
Just resolve the cycle by passing the app to the connectToDb function as a parameter instead of importing it:
//server.js
require("dotenv").config();
const express = require("express");
const app = express();
const connectToDb = require("./connectToDb")
connectToDb(app).catch(console.dir)
app.use((req, res) => {
res.status(404).send("unable to find");
});
module.exports = app
// connectToDb.js
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const port = process.env.PORT || 3000;
const connectToDb = async (app) =>{
try {
await client.connect();
console.log("Connected correctly to server");
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
} catch (err) {
console.log(err.stack);
} finally {
await client.close();
console.log("hello")
}
}
module.exports = connectToDb

HPM Error occurred while trying to proxy request (using react + express)

[HPM] Error occurred while trying to proxy request /api/users/ from localhost:3000 to http://localhost:5000 (ECONNRESET)
I get this error while trying to do axios.post request,
i'm running my app with concurrently (server with express and client side using react) ,
as described here I defined client/src/setupProxy.js file:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
my server.js:
const express = require('express');
const connectDB = require('./config/db');
const app = express();
//connect Database
connectDB();
//Init MiddleWare -allows to get the data from req.body
app.use(express.json());
//Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/posts", require("./routes/api/posts"));
app.get('/', (req, res) => res.send('API is running'));
//Port - first look for an environment port (when connect to heroku)
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`server listening on port: ${PORT}`);
})
and my post request in the client side:
export const register = ({ name, email, password}) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const body = JSON.stringify({name, email, password});
try {
const res = await axios.post('/api/users/', body, config);
console.log({res});
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
console.log('passed dispatch')
} catch (e) {
const errors = e.response.data.errors;
if(errors) {
errors.forEach(e => dispatch(setAlert(e.msg, 'danger')));
}
dispatch({
type: REGISTER_FAIL
})
}
}
any idea what I miss ?
EDIT:
I've noticed that my server using type ipv6 and client on ipv4, maybe that's the problem ? how I make them run on the same ipv ?

Peer cli works but ExpressPeerServer doesnt

I am trying to get an express peerJs server up and running locally over HTTPS. Now if i start the peerJS server via the CLI then i can connect to it just fine and everything works as it should, but once i try to run the peerJS server via my script, i cant connect to it. I get a net::ERR_CONNECTION_REFUSED error in the console.
Working code:
--server.js
const fs = require('fs');
const express = require('express');
const app = express();
const server = require('https').Server(
{ key: fs.readFileSync('vuekey.pem'), cert: fs.readFileSync('vuecert.pem') },
app
);
const io = require('socket.io')(server);
const { v4: uuidV4 } = require('uuid');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`);
});
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room });
});
io.on('connection', (socket) => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId);
socket.to(roomId).broadcast.emit('user-connected', userId);
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId);
});
});
});
server.listen(3000);
--client.js
const myPeer = new Peer(undefined, {
host: '/',
port: '3001',
});
I first run peerjs --port 3001 --sslkey 'E:\myPath\vuekey.pem' --sslcert 'E:\myPath\vuecert.pem' to manually start the PeerJS server. This all works fine and i have no issues. But i want to have the PeerJS server run as part of my main server script. So im doing that with ExpressPeerServer. So in my server.js file i add the below code, but thats when the console errors get thrown.
const { ExpressPeerServer } = require('peer');
const peerServer = ExpressPeerServer(server, {
debug: true,
port: '3001',
ssl: {
key: fs.readFileSync('vuekey.pem'),
cert: fs.readFileSync('vuecert.pem'),
},
});
app.use('/peerjs', peerServer);
What is the PeerJS CLI doing differently than my server.js code? How can i resolve this?
I was able to figure it out finally. The express server and the peer server were in separate ports and i needed to add the path parameter in the Peer object.
--server.js
const peerServer = ExpressPeerServer(server, {
debug: true,
port: '3000',
ssl: {
key: fs.readFileSync('vuekey.pem'),
cert: fs.readFileSync('vuecert.pem'),
},
});
--client.js
const myPeer = new Peer(undefined, {
host: '/', // This will force the localhost/IP of the machine
path: '/peerjs', // Path that was specified in the server.js file for the peerServer's app.use() method.
port: '3000', // This needs to be the same port as specified in the server.js
});
After making these minor changes, everything works as expected over HTTPS

How to facade (proxy) websocket port

I have server side rendering react app in which i have proxied all http calls to different port. Please see the code below for http proxy.
import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const http = require('http');
const httpProxy = require('http-proxy');
const PORT = process.env.PORT || 3001;
httpProxy.createServer({
target: 'ws://localhost:4000',
ws: true
}).listen(PORT); //Throws error since 3000 port is already used by //app.listen.
app.use(
"/api",
proxy("http://localhost:4000/", {
proxyReqOptDecorator(opts) {
opts.headers["x-forwarded-host"] = "http://localhost:4000/";
return opts;
}
})
);
app.post("/logger", (req, res) => {
logger.debug(req.body.data);
res.send({ status: "SUCCESS" });
});
app.listen(PORT, () => {
logger.debug(`Portal listening on ${PORT}`);
});
that means when i make any calls /api/endpoint it will redirect to localhost:4000/endpoint but will be seen in the network as http://localhost:3000/endpoint1
I want the same behaviour with websockets as well.
I am using new WebSocket(ws://localhost:3000/endpoint1); It should redirect to ws://localhost:4000/endpoint1.
and should be shown in network tab as ws://localhost:3000/endpoint1
Resolved it by using another library http-proxy-middleware
import httpproxy from "http-proxy-middleware";
import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3001;
const wsProxy = httpproxy('/ws', {
target: 'ws://localhost:4000',
pathRewrite: {
'^/ws' : '/', // rewrite path.
'^/removepath' : '' // remove path.
},
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
ws: true, // enable websocket proxy
logLevel: 'debug'
});
app.use(wsProxy);
app.use(
"/api",
proxy("http://localhost:4000/", {
proxyReqOptDecorator(opts) {
opts.headers["x-forwarded-host"] = "http://localhost:4000/";
return opts;
}
})
);
app.post("/logger", (req, res) => {
logger.debug(req.body.data);
res.send({ status: "SUCCESS" });
});
app.listen(PORT, () => {
logger.debug(`Portal listening on ${PORT}`);
});

REST api/postman - Cannot GET /the route Error

I am building a (RESTful) Node.js API, using this tutorial.
I have nade a server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8080;
app.listen(port, () => {
console.log('We are live on ' + port);
});
I can run my server and see the message :
We are live on 8080
my index.js
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
noteRoutes(app, db);
// Other route groups could go here, in the future
};
and my node_routes.js
//create a node
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
// You'll create your note here.
res.send('Hello')
});
};
index.js and node_routes.js are both inside app\routes\
I have also downloaded the post man app, to make simple requests
and I get the error
Cannot POST /notes
what am I doing wrong??
I can not figure it out!
There is an error in your server.js
You are missing require('./app/routes')(app, {});
Should be:
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});

Categories

Resources