Send a CORS request to Localhost from an electron application - node.js

I'm working on a project that involves an application built with Electron that interfaces with an express server, running on Localhost or the home network.
Problem right now is, I'm having trouble getting the server to acknowledge any requests from the application.
Here is my front end logic in the electron application:
let ipAddress;
let port;
let requestAddress;
function connect(){
const ipField = document.getElementById("nu-ip").value;
const portField = document.getElementById("nu-port").value;
port = portField;
if (ipField === "") {
ipAddress = 'localhost';
} else {
ipAddress = ipField;
}
port = portField;
if(port === ""){
requestAddress = `http://$(ipAddress)`;
} else {
requestAddress = `http://${ipAddress}:${port}`;
};
alert(requestAddress);
const request = newXMLHttpRequest();
alert(requestAddress);
request.open("GET",`${requestAddress}/connect`).send();
request.onReadyStateChange = (res) => {
alert(res);
}
}
function startup() {
console.log('Hey where does this show up?')
const NuToggle = document.getElementById("NuHelper-enable");
const NuTools = document.getElementById("Nu-tools");
const connectButton = document.getElementById("connect-button");
NuToggle.addEventListener("change", (event) => {
if(event.target.value === 'enable'){
//alert("NuHelper has been enabled");
NuTools.style.display='block';
connectButton.addEventListener('click', connect);
}
})
}
window.onload = startup;
And here is my server:
//require in our basic dependencies
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const errorHandler = require('errorhandler');
const cors = require('cors');
const PORT = 80;
const app = express();
app.use(morgan('dev'));
app.use(bodyParser);
app.use(errorHandler);
app.use(cors());
app.get('/connect',(req, res, next) => {
res.sendStatus(200);
})
app.listen(PORT, () => {
console.log(`Nu is listening on PORT ${PORT}`);
})
I put 80 into the PORT input and it'll alert "http://localhost:80", but it'll get no response at all from the server, and my logging middleware won't acknowledge that it received any request at all, which makes me think that I'm sending the request to the wrong address. Thanks in advance to anyone who understands how to solve this!

Related

using socket.io and WebSocket causes Error: server.handleUpgrade() was called more than once with the same socket

I am using socket.io and WebSocket in a node.js application. I have already set my app up to use socket.io for sending messages with twilio. Now It looks like Twilio does not have support for media streams with socket.io so I need to use WebSocket ('ws') to make this work. Is this possible I am getting an error Error: server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration
I already tried setting up my WebSocket like this
const wss = new WebSocket.Server({noServer: true})
But this obviously prevents me from getting the media stream to work... any suggestions?
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const { setIO } = require('./helpers/socket-setup');
const WebSocket = require('ws');
require("dotenv").config();
const app = express()
const corsOptions = {
origin:"http://localhost:3000",
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
app.use(cors(corsOptions))
const server = require('http').createServer(app)
const wss = new WebSocket.Server({server})
app.use(bodyParser.json({limit: '10mb'}))
app.use(express.urlencoded( { extended: true }))
require('./routes/userRoutes')(app);
wss.on('connection', (ws) => {
console.log("New Connection Initiated")
ws.on("message", message => {
console.log("this message socket event was called")
const msg = JSON.parse(message)
switch(msg.event) {
case "connected":
console.log("A new call has connected");
break;
case "start":
console.log("Starting Media Stream")
break;
case "media":
console.log("receiving Audio...")
break;
case "stop":
console.log("Call has Ended");
break;
}
})
})
let io = setIO(server)
io.on("connection", socket => {
io.to(socket.id).emit('messageFromBackend', { data: 'backend connected'});
socket.on('messageToServer', ( dataFromClient )=> {
console.log(dataFromClient);
})
})
const PORT = process.env.PORT || 5000;
server.listen(PORT);

No response from Socket.IO in Node.JS server

Guys i've been struggled for this past days, from this socket.io setup. I thought there's should be no mistakes on my code. I've followed all tutorial and documentation on how to setup the server for socket.io using node and express. But still when i try to connect to this there are no response from the socket.io. On my client side i try to connect the same url as this server running http://localhost:8090 (FIXED)
SO EVERYTHING IS SET UP! the thing that it won't work is bcs i didn't set the CORS(see my edited code) on the socket instance on the server side.FYI since Socket.IO v3 u need to include the cors property by defining which url that gonna connected to ur socket.
Server Code:
const express = require ('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const db = require("./Connection/pg_pool");
const authentication = require("./Config/auth");
const connectionError = require("./Config/connectionError");
const cors = require('cors');
let port = 8090;
let hostname = 'localhost';
const midtransClient = require('midtrans-client');
const paymentConf = require('./Config/payment');
const { encode } = require('node-encoder');
const axios = require('axios');
let payment = paymentConf.paymentConf;
let errorMsg = connectionError.connectionError();
let auth = authentication.auth;
const app = express();
const server = require("http").createServer(app);
const io = require('socket.io')(server)
io.on("connection", socket => {
console.log('NEW USER CONNECTED')
});
app.use(express.json());
app.use(cors({origin: true, credentials: true}));
app.use(express.urlencoded({extended: true}));
app.use(cookieParser());
server.listen(process.env.PORT || port, hostname, () => {
console.log(`Listening to ${hostname}:${port}`)
})
Client Code:
import React, {useState, useEffect, useRef, useCallback, useMemo} from 'react';
import { io } from "socket.io-client";
const ENDPOINT = "http://localhost:8090";
let socket;
export default function Chat(props) {
const [text, setText] = useState('')
const [req, setReq] = useState([]);
const [messages, setMessages] = useState([]);
const [send, setSend] = useState(false);
useEffect(() => {
socket = io(ENDPOINT);
console.log('ini socker', socket.connected)
socket.on("connect", (data) => {
console.log(data)
});
}, []);
....
FIXED CODE
/*since my frontend (client-side) was running on localhost:3000,
all u need to do is just define the cors and put the origin url that
u gonna connect to ur socket instance on Node.Js (server) like this.*/
const io = require('socket.io')(server, {
cors: {
origin: [`http://localhost:3000`],
credentials: true
}
})

socket.io problems. Not able to connect. front end says connection: false and backend doesn't log anything

i am new to socket.io and i can't get it to connect to react app. here is my app.js in node
const express = require('express');
const port = process.env.PORT || 4000;
const router = require('./routes/routes');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
const db = require('./db/db');
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => {
console.log('connected');
});
app.use('*', cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
(router);
app.listen(port, () => {
console.log('listening on port ' + port);
db.sync({
// force: true,
logging: false,
});
});
and my front end code.
import React, { useState, useEffect, useRef } from 'react';
import { io } from 'socket.io-client';
import classes from './Chatroom.module.css';
const Chatroom = ({ user, getAllMessages, setGetAllMessages }) => {
const ENDPOINT = 'http://localhost:4000/getallmessages';
var socket = io(ENDPOINT);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
socket.on('connect', () => {
socket.send('hello');
console.log('connected.');
});
console.log(socket);
}, []);
Whenever i look in the console on it shows connected: false and nothing is logging on the backend.
In order to fix the issue i had to add options to my io declaration as follows.
const server = require('http').createServer(app);
const options = {
cors: true,
origins: ['http://127.0.0.1:3000'],
};
const io = require('socket.io')(server, options);
127.0.0.1 being home and on client side my server is on 3000 so that's where that comes from. and on the client side you were right i had to remove "getallmessages" route so now it is as follows.
onst ENDPOINT = 'http://localhost:4000/';
var socket = io(ENDPOINT);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useEffect(() => {
socket.on('connect', () => {
socket.send('hello');
console.log('connected.');
});
console.log(socket);
}, []);
socket.io is bound to the server object so you should listen to the server instead of the app.
Change app.listen to server.listen
Change endpoint by removing getallmessages if you are not using namespaces

Google Cloud IoT sendCommandToDevice node.js sends command but catches error

I have this in Google's App Engine (node.js).
My device gets all the commands but I still get the Could not send command. Is the device connected? error.
BTW, already tried this: Await for function before end()
And same result.
Trying to follow this example BTW:
https://cloud.google.com/nodejs/docs/reference/iot/0.2.x/v1.DeviceManagerClient#sendCommandToDevice
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
const iot = require('#google-cloud/iot');
app.get('/', urlencodedParser, (req, res) => {
res.setHeader('Content-Type', 'application/json');
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).end(JSON.stringify({
data: OK
}))).catch(err => res.status(404).end('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
On my end I should get status 200 and OK but it doesn't happen.

How to change the BaseURL [HOST] in expressjs

I am using the below code and I am using express-http-proxy:
const express = require('express');
const proxy = require('express-http-proxy');
var baseUrl2 = "https://localhost:5002";
var app = express();
app.use('/api', proxy(baseUrl2, {
// I want to change the baseUrl2 before making the request.
proxyReqPathResolver: (req) => {
const modifiedURL = "/someChanges"
return require('url').parse(modifiedURL).path;
},
}));
app.listen(3000);
I am able to change the url from https://localhost:5002 to https://localhost:5002/someChange.
But I need to change it from https://localhost:5002 to https://localhost:5001 or https://example.com.
I was able to change the port using proxyReqOptDecorator option. I am changing port using proxyReqOpts.port but we can also change the host using proxyReqOpts.host
Updated Code:
const express = require('express');
const proxy = require('express-http-proxy');
var baseUrl2 = "https://localhost:5002";
var app = express();
app.use('/api', proxy(baseUrl2, {
// I want to change the baseUrl2 before making the request.
proxyReqPathResolver: (req) => {
const modifiedURL = "/someChanges"
return require('url').parse(modifiedURL).path;
},
proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
if(someCondition)
proxyReqOpts.port = 5001;
else
proxyReqOpts.port = 5002;
return proxyReqOpts;
}
}));
app.listen(3000);

Resources