Node.js server just keeps loading with no result - node.js

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')();

Related

How to resolve server error in Socket.io?

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

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

How to create a connectable websocket server on Azure app services?

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?

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.

Express + MQTT from POST request to publish in topic

I need a Node.js web service that accept a specific POST request that will trigger a publishing in a specific MQTT topic.
I use Express to listen for the request and this part of the script works fine.
The problem is when I it should trigger the publish in topic to perform a downlink.
The code without the Express part works fine. So It seems like Express interfere with MQTT. But the connection to the Broker works fine. Only the publish procedure doesn't work.
var express = require('express');
var bodyParser = require('body-parser');
var mqtt = require('mqtt')
var fs = require('fs')
var path = require('path')
const util = require('util')
var app = express();
var CERT = //certificate
var PORT = //port
var HOST = // host
var options = {
port: PORT,
host: HOST,
clientId: //client_id
username: //uname
password: //pswd
cert: CERT,
rejectUnauthorized: false,
protocol: 'mqtts'
}
var client;
var jsonParser = bodyParser.json();
var port = process.env.PORT || 8080;
app.use(express.static('public'));
app.get('/', function (req, res) {
res.render(__dirname + "/public/index.html");
})
client = mqtt.connect(options);
client.on("connect", () => {
console.log("MQTT connected");
})
client.on('message', function (topic, message) {
var msg = JSON.parse(message)
console.log("topic: " + topic + " msg:" + util.inspect(msg))
});
app.post('/', jsonParser, function (req, res) {
// Prepare output in JSON format
data = {
dev_id: req.body.dev_id,
pswd: req.body.password,
tx_cycle: req.body.tx_cycle
};
if (data.pswd != "password") {
console.log("Wrong password")
}
else {
console.log(data);
var topic = 'publish_topic';
var tx_cy = data.tx_cycle;
var msg = '{"port":"222","payload":"' + tx_cy + '","confirmed": false,"window":"BOTH","priority":0}';
console.log('Try to send downlink message, for ' + data.dev_id + ' set to ' + data.tx_cycle + ' min -> hex ' + tx_cy);
client.subscribe('reply/+/id/+');
client.publish(topic, msg);
res.status(200).send(msg + " sent to broker");
}
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
I solve the problem. The client id was refused by the broker because was not unique. Changing it solved the issue.

Resources