I'm currently running a node and websocket server on azure app services, server looks like this
const http = require('http');
const app = require("express")();
const sqlite3 = require('sqlite3').verbose();
const path = require('path')
const serveStatic = require('serve-static')
const url = require('url');
const httpServer = http.createServer((req, res) => {
res.writeHead(200, {"Content-type": "text/plain"});
res.end("Hello");
});
const port = process.env.PORT || 8080;
httpServer.listen(port, () => console.log("Listening.. on 80"));
const websocketServer = require("websocket").server
const wsServer = new websocketServer({
"httpServer": httpServer
})
wsServer.on("request", request => {
//connect
const connection = request.accept(null, request.origin);
connection.on("open", () => console.log("opened!"))
connection.on("close", () => console.log("closed!"))
connection.on("message", message => {
const result = JSON.parse(message.utf8Data)
})
var payLoad = {
"method": "connect",
"thing": "TEST"
}
connection.send(JSON.stringify(payLoad));
})
However anytime I try to connect I get
(index):79 WebSocket connection to 'ws://triverserver-50.azurewebsites.net/' failed: Error during WebSocket handshake: Unexpected response code: 503
I saw that docker was started on port 8080 in the logs and have tried adding WEBSITES_PORT:80 and PORT:80 to general settings but they had no effect. Any Ideas?
Related
I am creating a web application, using socket.io . A Server error occurred while connecting to the server. We found out that the error is in the backend. What could be written incorrectly here? Code:
const path = require('path');
const express = require('express');
const app = express();
const fs = require("fs");
var privateKey = fs.readFileSync('path').toString();
var certificate = fs.readFileSync('path').toString();
const http = require('https').Server({key:privateKey,cert:certificate}, app);
const io = require('socket.io')(http);
const port = 9998;
const debug = true;
var connectedArray = new Array()
const delay = 60 * 1000
const mysql = require('mysql2');
const db = mysql.createConnection({
host: 'localhost',
user: 'user_name',
password: 'user_password',
database: 'database',
});
io.on('connection', (socket) => {
socket.on('register', msg => {
console.log("User registered")
connectedArray.push({
connectmessage: msg,
socket: socket,
})
})
socket.on('disconnect', () => {
if (debug) console.log('User disconnected')
})
})
app.use(express.static(path.resolve(__dirname, 'static')))
app.get('/', (req, res) => {
res.sendFile('./index.html')
})
http.listen(port, () => {
console.log(`Server started listening on port ${port}...`)
})
P.S: The problem began to arise after binding the domain
P.S 2: I have two sites on server, on different Apache virtual hosts
P.S 3: I am using https
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
}
})
i am trying to send an https request from my frontend (reactjs) to backend (nodejs/express).
These two both run in localhost.
Back end server code:
const app = require('./app')
const https = require('https');
const fs = require('fs');
const credentials = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
//connect to the database
require('./db')
const port = 8765;
app.get('/', (req, res) => {
res.send('Now using https..');
});
var server = https.createServer(credentials, app);
//var server = https.createServer(app);
// listen for requests
server.listen(port, () => {
console.log("server starting on port : " + port)
});
front end request:
const {data: Sessions}= await axios.get("https://localhost:8765/...");
doint this request from postman with the exact same parameters produces the desired result.However when i try to do this from frontend i get:
GET https://localhost:8765/... net::ERR_CERT_AUTHORITY_INVALID in react chrome extention.
Why is this happening and how can i solve this?
I'm running a nodejs socket.io server on a raspberry pi, and a socket.io web client on Firefox.
But Firefox keeps giving me a Cross-Origin Request Blocked (Same Origin Policy Error).
// nodeJS Server:
var app = require('express')();
var cors = require('cors');
app.use(cors({origin: '*:*'}));
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
io.on('connection', function(socket) {
socket.emit('announcements', { message: 'A new user jas joined!' });
});
//JS Browser client:
const socket = io('ws://<INSERT_MY_EXTERNAL_IP>:3000');
socket.on('connect', () => {
socket.send('Hello!');
});
I've also tried: io.origins(...), io.set("origin", ...), but those keep saying the functions origins and set are undefined.
Not sure what to do at this point.
You can pass in a cors prop when you initialize the server socket.
Pass in a config object with cors set to true, eg. cors: true or cors: { origin: '*' }.
Read more about that here.
In action (only tested in LAN):
client.js
const socket = io('ws://localhost:3000');
socket.on('testing', res => { console.log(res) });
server.js
const app = require('express')()
const server = require('http').createServer(app)
const opts = { cors: { origin: '*' } }
const io = require('socket.io')(server, opts)
const cors = require('cors')
app.use(cors())
io.on('connection', (socket) => {
console.log(`Client connected (id=${socket.id})`)
socket.emit('testing', 123)
socket.on('disconnect', () => {
console.log(`Client disconnected (id=${socket.id})`)
})
});
(
port => server.listen(
port,
() => console.log(`Express server running on port ${port}`)
)
)(3000)
server.js
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);
app.js
const express = require('express');
const app = express();
const productRoutes = require('./api/routes/products');
app.use('/products', productRoutes);
module.exports = app;
so when i just run the code node server.js it just keep looping without any result.
Check out this link It gives a bit more detail on how that works.
const http = require('http');
const net = require('net');
const url = require('url');
// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
proxy.on('connect', (req, cltSocket, head) => {
// connect to an origin server
const srvUrl = url.parse(`http://${req.url}`);
const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
});
// now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {
// make a request to a tunneling proxy
const options = {
port: 1337,
hostname: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80'
};
const req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
proxy.close();
});
});
});
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);
As far I could extract from code, the thing that is most probably happening in your server.js is that your server is waiting for some request. And you have nothing in your code handle requests.
I think you have to call the require function to return the actual router object, try to change this line
from: const productRoutes = require('./api/routes/products');
to: const productRoutes = require('./api/routes/products')();