I am developing an REST-API that is running via a load-balancer with a database in MongoDB.
The API works when not using the load-balancer, but when implemented i do not get a response in Postman/Insomia when posting a GET request to the database - on the index ("/") route there in no problem getting a response back though.
But as the title shows, it get this error when canceling the request in PostMan, if like the connection could not be established.
This is the full error:
Error: socket hang up
at connResetException (internal/errors.js:628:14)
at TLSSocket.socketCloseListener (_http_client.js:449:25)
at TLSSocket.emit (events.js:412:35)
at net.js:675:12
at TCP.done (_tls_wrap.js:563:7) {
code: 'ECONNRESET'
}
This is my load-balancer
const https = require ("https");
const httpProxy = require("http-proxy");
const seaport = require("seaport");
const express = require("express");
const fs = require("fs");
const HOST = 'localhost';
const path = require("path")
const PORT = 8080;
const connect = seaport.connect('localhost', 9090);
let i = - 1;
const certificate = {
key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
secure: false
};
let proxy = httpProxy.createProxyServer({secure: false});
let server = https.createServer(certificate, function(req, res) {
let addresses = connect.query('server');
if (!addresses.length) {
res.end('Server failed');
};
i = (i + 1) % addresses.length;
let host = addresses[i].host.split(":").reverse()[0];
let port = addresses[i].port;
proxy.web(req, res, { target: 'https://' + host + ':' + port });
});
server.listen(PORT, function() {
console.log('loadbalancer listens on'+ ":" + PORT)
});
And this is my app.js
const express = require("express");
const app = express();
const morgan = require("morgan")
const bodyParser = require("body-parser")
const https = require('https');
const fs = require('fs');
const seaport = require('seaport');
const path = require('path');
const mongoose = require("mongoose");
//Database
const db = require('./database/db');
const { MongooseDocument } = require('mongoose');
//Routes
const clientRoute = require ("./api/routes/client")
const reservationsRoute = require ("./api/routes/reservations")
app.use('/client', clientRoute);
app.use('/reservations', reservationsRoute);
//index route
app.use('/', (req, res) =>{
res.send('Welcome to the app');
});
//Error handling 1
app.use((req, res, next) => {
const error = new Error("Not found" + " ");
error.status = 400;
next(error);
})
//Error handling 2
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message:("Error 2" + " - " + error.message )
}
});
});
//Create server with the https key and certificate
const sslServer = https.createServer({
key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
}, app);
//Middleware
app.use(morgan("dev"));
app.use(bodyParser.json());
const seaportObject = seaport.connect('localhost', 9090);
//Start listening
let port = seaportObject.register('server');
sslServer.listen(port, () => {
db.mongoConnection()
.then(
console.log('Localserver listens on: ' + port)
)
.catch(err =>{
console.log(err)
res.status(500).json({
error:err,
message: "
It went wrong here "
})
});
});
My Database folder
const mongoose = require('mongoose');
let connection;
const mongoConnection = async () => {
if (!connection) {
connection =
await mongoose.connect("removed",
() => console.log("Mongo is up and running")),{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
}
return connection;
}
module.exports = {
mongoConnection: mongoConnection
};
I am stuck on this subject, please share some guidance
A solution has been found - the problem was that the database never connected
Related
I am trying to impliment websocket server for my frontend chart for trading values but whenever i try to change graph pairs its fluctuating my frontend and not clearing privious request here's my server file
const express = require('express');
const path = require('path');
const mysql = require('mysql')
const bodyParser = require('body-parser');
const passport = require('passport');
const exchangeCtrl = require("./controllers/exchange.controller.js");
const webSocketServer = require("websocket").server;
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/static', express.static('public'))
const port = 8000;
var server = app.listen(port, () => console.log(`Server up and running on port
${port} !`));
const wsServer = new webSocketServer({
noServer: true,
path: "/websockets",
httpServer: server,
});
const client = {};
const getUniqueId = () => {
const s4 = () =>
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return s4() + "-" + s4() + "-" + s4();
};
var socketDataVar = "";
wsServer.on("request", function (request) {
var userUd = getUniqueId();
const connection = request.accept(null, request.origin);
client[userUd] = connection;
client[userUd].send(JSON.stringify(userUd));
connection.on("message", async function (message) {
var interval = 1000;
if (message.type === "utf8") {
if (message.utf8Data) {
if (JSON.parse(message.utf8Data) == "disconnect") {
clearInterval(socketDataVar);
} else {
socketDataVar = setInterval(
() => socketData(message.utf8Data),
interval
);
}
}
}
});
const socketData = async (socket) => {
var value = JSON.parse(socket);
var firstCoinId = value.firstCoinId;
var secondCoinId = value.secondCoinId;
var userId = value.userId;
var clientId = value.clientId;
var graphDataApi = await exchangeCtrl.graphData(firstCoinId, secondCoinId);
var topBarApi = await exchangeCtrl.topBar(firstCoinId, secondCoinId);
var filalData = {
graphDataApi,
topBarApi
};
for (key in client) {
client[key].sendUTF(JSON.stringify(filalData));
}
};
});
I am trying to clear the interval and then set the new values but i might think that its not working and i get 2 set of data on each click of frontend
I'm just getting used to NodeJS and MongoDB so please go gentle! I'm trying to "console.log" the "network Interfaces" to find the IP address.
No matter what I do, I keep getting an error:
"TypeError: Cannot read property '1' of undefined "
I suspect that it's this code in line 11:
const ip = networkInterfaces.Ethernet[1].address;
Here is what is in my app.js file:
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const os = require("os");
const networkInterfaces = os.networkInterfaces();
const ip = networkInterfaces.Ethernet[1].address;
require("dotenv/config");
//import routes
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");
const favoriteRoute = require("./routes/favorite");
const authRoute = require("./routes/auth");
const notification = require("./middlewares/pushNotification");
//Connect to DB
const dbURI = process.env.DB_CONNECTION;
mongoose.connect(
dbURI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
},
() => {
app.listen(process.env.PORT, ip);
let dirPath = path.join(
__dirname,
"public/api/static/images/productPictures"
);
let dirPathUser = path.join(
__dirname,
"public/api/static/images/userprofile"
);
createDir(dirPath);
createDir(dirPathUser);
console.log("Connected to DB");
}
);
function createDir(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true }, (err) => {
if (err) {
console.error("createDir Error:", err);
} else {
console.log("Directory is made!");
}
});
}
}
...
this answer will help you with
network interfaces
If you are trying to get the client IP then you can use
const RequestIp = require("#supercharge/request-ip");
const ip = RequestIp.getClientIp(req);
inside your API
or to get the current machine address you can use child process
I solved the issue by removing Ethernet[1].address with en0[1].
line 11 now reads:
const ip = networkInterfaces.en0[1].address;
I added this to the end of my App.js files:
const port = process.env.PORT || '3000';
const address = process.env.ADDRESS || '127.0.0.1';
app.listen(port,address, () => console.log('Server running on http:// ' + address + ':' + port +'/'));
I'm building a web application using HTTPS, Express, Socket.io, and WebSocket. Currently Express is using port 3000. In order to use the same port of WebSocket as 3000 port, I wrote the code as follows.
app.js
const path = require('path');
const express = require('express');
const app = express();
const mainRouter = require('./routes/main/main');
// Middleware
...
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'res')));
app.use('/', mainRouter);
// 404 error handler
app.use((req, res) => {
logger.error(`404 Page not found`);
res.status(404).send('404 Page not found');
});
module.exports = app;
bin/www
const fs = require('fs');
const path = require('path');
const app = require('../app');
const https = require('https');
const options = {
key: fs.readFileSync(path.resolve(__dirname, '../config/ssl/localhost-key.pem')), // Private key
cert: fs.readFileSync(path.resolve(__dirname, '../config/ssl/localhost.pem')), // Certificate
};
const server = https.createServer(options, app);
const io = require('socket.io')(server);
const WebSocket = require('../public/js/websocket');
const normalizePort = (value) => {
const port = parseInt(value, 10);
if(isNaN(port)) {
return value;
}
if(port >= 0) {
return port;
}
return false;
};
const port = normalizePort(process.env.PORT || 3000);
// Setting port
app.set('port', port);
const onError = (err) => {
if(err.syscall !== 'listen') {
throw err;
}
const bind = typeof(port) === 'string' ? `Pipe ${port}` : `Port ${port}`;
switch(err.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
};
const onListening = () => {
const address = server.address();
const bind = typeof(address) === 'string' ? `Pipe ${address}` : `Port ${port}`;
};
...
WebSocket(server);
server.listen(port, '0.0.0.0');
server.on('error', onError);
server.on('listening', onListening);
public/js/websocket.js
const ws = require('ws');
module.exports = function WebSocket(server) {
const wss = new ws.Server({ server : server });
wss.on('connection', (ws, req) => {
ws.on('message', (data) => {
ws.send(data);
console.log(data);
});
});
wss.on('listening', () => {
console.log('listening..');
});
};
routes/main/main.js
const router = require('express').Router();
const { v4 : uuidv4 } = require('uuid');
router.get('/', (req, res) => {
res.redirect(`/${uuidv4()}`);
});
router.get('/:room', (req, res) => {
res.render('main/main', { room: req.params.room });
});
module.exports = router;
After configuring the server as above, if you connect to https://localhost:3000 after npm start, the following error occurs.
Error: Invalid WebSocket frame: invalid UTF-8 sequence ... code: 'WS_ERR_INVALID_UTF8', [Symbol(status-code)]: 1007
I don't understand why this error occurs. Also, how can I fix the code to fix the error?
I'm attempting to start a Next.js application in https mode. I'm following the instructions here. When I try to open the page, I get the following error:
TypeError: (0 , react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV) is not a function
here's my code:
const { createServer } = require("https");
const { parse } = require("url");
const {next} = require("next");
const fs = require("fs");
const dotenv = require('dotenv');
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
//read the .env file
dotenv.config();
const port = process.env.PORT;
const httpsOptions = {
key: fs.readFileSync("./certificates/privateKey.key"),
cert: fs.readFileSync("./certificates/certificate.crt"),
};
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(port, (err) => {
if (err) throw err;
console.log("> Server started on https://localhost:" + port);
});
});
Here's the stack trace:
TypeError: (0 , react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV) is not a function
at IBOUIApp (C:\Users\mgardner\workspace\qa-tool-backoffice\.next\server\pages\_app.js:53:92)
at d (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:33:498)
at bb (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:36:16)
at a.b.render (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:42:43)
at a.b.read (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:41:83)
at exports.renderToString (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\react-dom\cjs\react-dom-server.node.production.min.js:52:138)
at Object.renderPage (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\next-server\server\render.js:54:854)
at Function.getInitialProps (C:\Users\mgardner\workspace\qa-tool-backoffice\.next\server\vendors-node_modules_next_dist_pages__document_js.js:627:19)
at loadGetInitialProps (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\next-server\lib\utils.js:5:101)
at renderToHTML (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\next-server\server\render.js:54:1145)
at async C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\next-server\server\next-server.js:112:97
at async C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\next-server\server\next-server.js:105:142
at async DevServer.renderToHTMLWithComponents (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\next-server\server\next-server.js:137:387)
at async DevServer.renderToHTML (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\next-server\server\next-server.js:138:610)
at async DevServer.renderToHTML (C:\Users\mgardner\workspace\qa-tool-backoffice\node_modules\next\dist\server\next-dev-server.js:36:578)
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.