I have been trying to connect my express app, but for some reason it is just not connecting.
I am going to "IP:PORT" on chrome and I get a typical "Refused to connect" error.
I am using node.js, and the latest version of express.
"Received" does not print to the console, however it logs "App listening on port 8088"
I have tried a lot of things, hosting on digital ocean, no connection. I am currently trying it in VSC (Ip address is my ipv4 address)
When trying using HTTP, I get a connect fail error.
My code:
const express = require('express');
const app = express()
app.use(express.json())
const fs = require('fs');
require('dotenv').config()
const serverKey = process.env.SERVER_KEY
const port = process.env.PORT
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
module.exports = {
async execute(client) {
console.log('Test')
app.post("/getVerificationCode", function (req, res, next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes, null, 4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function (req, res, next) {
return res.status(200).json({})
})
app.listen(port)
console.log(`App listening on port ${port}`)
}
}
"Test" does log, so the module IS being required. Before, I was trying it in my server.js, but that did not work and the code was messy, so I moved it into a folder.
I would really appreciate some help, thank you!
Related
Ive managed to slowly grind my way through the curriculum and just completed the backend portion.
I decided to look into building some practice project using Heroku…
If this is not the place to post his please let me know.
While following this tutorial https://devcenter.heroku.com/articles/getting-started-with-nodejs, I get to the portion where we connect to the Postgres server (‘Provision a database’). I do this successfully but I get side tracked on figuring out how to access/use this Postgres database locally when it is located and provided through Heroku. Please consider the following two methods:
Method #1
const cool = require("cool-ascii-faces");
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 5000;
const { Pool } = require("pg");
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false,
},
});
express()
.use(express.static(path.join(__dirname, "public")))
.set("views", path.join(__dirname, "views"))
.set("view engine", "ejs")
.get("/", (req, res) => res.render("pages/index"))
.get("/db", async (req, res) => {
try {
const client = await pool.connect();
const result = await client.query("SELECT * FROM test_table");
const results = { results: result ? result.rows : null };
res.render("pages/db", results);
client.release();
} catch (err) {
console.error(err);
res.send("Error " + err);
}
})
.get("/cool", (req, res) => res.send(cool()))
.get("/times", (req, res) => res.send(showTimes()))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const showTimes = () => {
let result = "";
const times = process.env.TIMES || 5;
for (i = 0; i < times; i++) {
console.log(i);
result += i + " ";
}
return result;
};
result form method #1
Method #2
Exactly the same code from Method #1 except I take the following steps prior to running:
Kill and reopen terminal at file location (/node-js-getting-started)> Using the credentials information (User, Password, Host, Port, and Database) in the heroku datastore resources tab I run the following in order:
% export DATABASE_URL=postgres://User:Password#Host:Port/Database
% heroku local web <--This runs app # localhost:5000
results from method #2
My question is, why does the one connect and the other doesn’t?
I'm trying to run Next js application on my Digital Ocean Droplet (with OpenLiteSpeed).
I have start.js file with the following content:
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
handle(req, res, parsedUrl)
}).listen(80, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:80')
})
})
When I calling this file from console: node start.js, my site successfully running on port 80.
But when I'm trying to add this file as a start up file in App Server Context Definition, site is not running, and my website just cannot be reached.
But when I'm changing the file to default one (app.js):
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World! From OpenLiteSpeed NodeJS\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://:/`);
});
The website is successfully opening with Hello World.
Listener is successfully setup to port 80:
Grace restart is done. changing ports to 3000 (for example) not helping much: I got same behavior.
What I am doing wrong?
UPDATE:
I found temporary solution:
node start.js & disown
and then close the Terminal.
Please anyone give me drawbacks of this method.
So not sure why, but my nodeJS / NextJS app keeps triggering plesks ip_ban. I recoded our site and moved it away from ReactJS to NextJS. But seems by doing so their must be a command that is making it look like an IP address is trying to connect to many times which makes the plesk server add the IP to a ban list (the rule that keeps getting triggered is - recidive).
I am wondering what is the correct way to solve this issue. Disabling ip_ban is a temp solution but not the ideal solution.
my server.js script is very clear and has no issues (once ip_ban is disabled).
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const port = !dev ? process.env.PORT : 3000;
// Create the Express-Next App
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
handle(req, res, parsedUrl);
console.log("pathname", pathname);
}).listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://example.com:${port}`);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
The rule that keeps getting triggered:
[recidive]
enabled = true
filter = recidive
action = iptables-allports[name=recidive]
logpath = /var/log/fail2ban.log
maxretry = 3
To elaborate on the question in the title,
I have made a simple app with js that runs on a node server. I have a thumbdrive that contains a folder and a start.bat file. Start.bat, as the name implies, switches the directory to my server folder and starts the server. Start.bat also starts another process that opens the edge browser to localhost in kiosk mode. When a user starts start.bat, the app will appear on the screen with the server running in the background. When the user exits the edge browser, they are then required to CTRL + C out of the server cmd prompt to properly shut down the server.
I need a system which effectively automatically shuts down the server after the Edge browser has been closed. I am not sure if it is possible to tie together the closing of the browser and the node server and am yet to find a solution online. If anyone has any ideas regarding possible fixes to my problem I would love to hear it!
https-server.js
const https = require("https");
const path = require("path");
const fs = require("fs");
const ip = require("ip");
const process = require("process");
const app = express();
const port = 443;
process.chdir("..");
console.log("Current working dir: " + process.cwd());
var rootDir = process.cwd();
//determines what folder houses js, css, html, etc files
app.use(express.static(rootDir + "/public/"), function (req, res, next) {
const ip = req.ip;
console.log("Now serving ip:", "\x1b[33m", ip, "\x1b[37m");
next();
});
//determines which file is the index
app.get("/", function (req, res) {
res.sendFile(path.join(rootDir + "/public/index.html"));
});
var sslServer = https.createServer(
{
key: fs.readFileSync(path.join(rootDir, "certificate", "key.pem")),
cert: fs.readFileSync(path.join(rootDir, "certificate", "certificate.pem")),
},
app
);
//determines which port app (http server) should listen on
sslServer.listen(port, function () {
console.log(
"Server has successfully started, available on:",
"\x1b[33m",
ip.address(),
"\x1b[37m",
"listening on port:",
"\x1b[33m",
+port,
"\x1b[37m"
);
console.log("CTRL + C to exit server");
sslServer.close();
});
Will provide any needed information.
Have an endpoint registered to exit the process
app.get('/shutdown', (req, res, next) => {
res.json({"message": "Received"});
next();
}, () => {
process.exit();
});
Then register a listener for onbeforeunload to do a request to this endpoint.
let terminateCmdReceived = false;
async function shutdown(e) {
let response;
if (!terminateCmdReceived) {
e.preventDefault();
try {
response = await fetch('http://localhost:3000/shutdown');
const json = await response.json();
if(json.message === "Received") {
terminateCmdReceived = true;
window.close();
}
} catch (e) {
console.error("Terminate Command was not received");
}
}
}
window.onbeforeunload = shutdown
Web soket connection error
I've got a problem with my server. It uses express and express-ws for web sockets. The problem is that this server works fine on the local host. But when i run it with the help of ssh (see localhost.run) and access the site by the given link from another computer (through Chrome), the web socket doesn't open and the next error shows up in the console
main.js:12 WebSocket connection to 'ws://localhost:3000/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
even though i added cert and key to the server connection. P.S. The site loads too, it's only that the socket doesn't work.
here is the server.js code:
"use strict";
const fs = require("fs");
const credentials = {
key: fs.readFileSync("./key.pem"),
cert: fs.readFileSync("./cert.pem")
};
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const https = require("https");
const PORT = process.env.PORT || 3000;
app.use(express.static(__dirname + "/public/Messenger"));
app.use(express.static(__dirname + "/public/Login"));
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const server = new https.createServer(credentials);
const expressWs = require("express-ws")(app, server);//if i take the
//second argument (server) away, it works fine on localhost:3000, but
//with this it fires the error:
//WebSocket connection to 'ws://localhost:3000/' failed: Connection
//closed before receiving a handshake response
const routes = require("./MVC/Router/router.js"); //importing route
routes(app);
app.listen(PORT, () => {
console.log("listening on port " + PORT);
});
here is the router.js:
"use strict";
module.exports = function(app) {
const database = require("../Controller/controller.js");
// database Routes
app.route("/").get(database.loadPage);
app.route("/login").get(database.loginPageLoad);
app
.route("/signIn")
.get(database.signInPageLoad)
.post(database.signIn);
app
.route("/submitLogin")
.post(database.loginSubmit)
.get(database.showUsers);
app.ws("/", database.sendmsg);
};
which redirects the processing flow to the next part of controller.js:
const CLIENTS = [];
let counter = 0;
exports.sendmsg = (ws, req) => {
console.log(cache.get("lorem"));
ws.on("message", msg => {
if (msg === "connected") {
console.log("connected");
CLIENTS.push([ws, counter]);
ws.send(JSON.stringify({ counter }));
counter++;
} else if (JSON.parse(msg).msg && JSON.parse(msg).ID) {
CLIENTS.forEach(box => {
if (box[1] === msg.ID) {
console.log(`user ${box[1]} is closed`);
box.push("closed");
box[0].close();
} else {
return;
}
});
} else {
sendAll(msg);
}
ws.on("close", () => {
console.log("disconnected");
ws.close();
});
});
};
function sendAll(message) {
for (let i = 0; i < CLIENTS.length; i++) {
if (CLIENTS[i][0].readyState === 1) {
CLIENTS[i][0].send(message);
}
}
}
The last piece of code is just what it does on the server, don't care of it too much. The problem is that the web socket doesn't get open when i enter the link from another computer. How can i solve it?