node.js https server not loading responding - node.js

I am trying to start a https node.js server.
I started by creating a certificate and key following this guide:
http://gaboesquivel.com/blog/2014/nodejs-https-and-ssl-certificate-for-development/
and I placed them in my /app_name/security/keys directory.
To start my https server, I have the following:
const https = require('https'),
fs = require('fs');
if(app.get('env') === 'development') {
console.log('dev env!!'); //prints correctly
console.log('port: ' + port); //prints correctly
const options = {
key: fs.readFileSync('./security/keys/key.pem'),
cert: fs.readFileSync('./security/keys/cert.pem')
};
https.createServer(options, (req, res) => {
console.log('https good to go'); //this does not print out anything
}).listen(port);
}
When I go to https://localhost:3000, the page throws an error
This site can’t be reached
localhost unexpectedly closed the connection.
ERR_CONNECTION_CLOSED
But there's no error on the server side console. Furthermore, if i go to the regular localhost:3000, I get:
The localhost page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
Can someone help?
Thanks in advance!
---- UPDATE ----
I'm running on port 443 now. Initially I got an error:
Error: listen EACCES 0.0.0.0:443 so I ran:
sudo NODE_ENV=development nodemon app
Which did not throw any errors. However, when I went to https://localhost:443, I get:
This site can’t be reached
localhost unexpectedly closed the connection.

I used express as a web server.
to install express:
npm install express --save
I took your code, added the usage in express, generated certificate using openssl, and executed it - all looked good, the server was up, listening to port 3000 over https.
My code (which is based on your code...):
var app = require('express')();
const https = require('https'),
fs = require('fs'),
port = 3000;
if(app.get('env') === 'development') {
console.log('dev env!!'); //prints correctly
console.log('port: ' + port); //prints correctly
const options = {
key: fs.readFileSync('/tmp/private.key'),
cert: fs.readFileSync('/tmp/publickey.crt')
};
https.createServer(options, (req, res) => {
console.log('https good to go'); //this does message appears!!! ^_^
}).listen(port);
}
Please pay attention to the way I defined app: var app = require('express')();
You can split this definition into two line if it's more readable:
var express = require('express');
var app = express();

So many problems with your code.
I tested this really quickly.
the keyword app and port is not defined, lines 4 and 7 respectively.
That will throw you a syntax error, preventing the code from continuing any further therefore server not starting up at all.
As I mentioned on my comment, use devtool to debug and use the following line on a CLI devtool server.js -w where the -w watches for file changes and reloads the server on the fly, while developing.
also assuming you named your entry file server.js

Related

http-proxy module doesn't work with create-react-app, but works with serve -s build

http-proxy module doesn't work with create-react-app, but works with serve -s build
This is my proxy-server code.
So what it does - it joins 2 api servers on different ports and frontend to a single 80 port. When you open localhost:80/* it should open react frontend (3000 port). When you open /api it gives you data from 4000 port and /secondapi from 1000 port.
My 2 backend api servers are opening completely fine with it.
Also when I start frontend server using serve module it also works fine and returns my frontend part.
But if I start frontend at the same 3000 port using "npm start" my proxy server returns connect ECONNREFUSED ::1:3000
const httpProxy = require('http-proxy');
const http = require('http');
const { maintenanceHtml } = require('./maintenanceHtml');
const proxy = httpProxy.createServer();
const guiUrl = 'http://localhost:3000'; // react frontend app
const apiUrl = 'http://localhost:4000'; // 1st api server
const apiPrefix = '/api';
const fnApiUrl = 'http://localhost:1000'; // 2nd api server
const fnApiPrefix = '/secondapi';
const port = 80;
http.createServer((req, res) => {
let target = guiUrl;
if (req.url.startsWith(apiPrefix)) {
req.url = req.url.replace(apiPrefix, '/');
target = apiUrl;
}
if (req.url.startsWith(fnApiPrefix)) {
req.url = req.url.replace(fnApiPrefix, '/');
target = fnApiUrl;
}
proxy.web(req, res, { target })
proxy.on('error', (error) => {
console.log(error.message)
res.end(maintenanceHtml);
})
}).listen(port, () => {
console.log(`Proxy server has started on port 80`)
});
I think that there is react server settings that I'm not able to find.
There is a little example that you're able to start at your own PC.
https://github.com/b2b-Alexander/react-js-problem
Found solution on github: https://github.com/vitejs/vite/discussions/7620
I got installed new v18.12.1 version of NodeJS.
My main machine has v16.14.0
So I rolled back the version of NodeJS for my project.

"serve -s build" starts over my create-react-app "npm start" [duplicate]

http-proxy module doesn't work with create-react-app, but works with serve -s build
This is my proxy-server code.
So what it does - it joins 2 api servers on different ports and frontend to a single 80 port. When you open localhost:80/* it should open react frontend (3000 port). When you open /api it gives you data from 4000 port and /secondapi from 1000 port.
My 2 backend api servers are opening completely fine with it.
Also when I start frontend server using serve module it also works fine and returns my frontend part.
But if I start frontend at the same 3000 port using "npm start" my proxy server returns connect ECONNREFUSED ::1:3000
const httpProxy = require('http-proxy');
const http = require('http');
const { maintenanceHtml } = require('./maintenanceHtml');
const proxy = httpProxy.createServer();
const guiUrl = 'http://localhost:3000'; // react frontend app
const apiUrl = 'http://localhost:4000'; // 1st api server
const apiPrefix = '/api';
const fnApiUrl = 'http://localhost:1000'; // 2nd api server
const fnApiPrefix = '/secondapi';
const port = 80;
http.createServer((req, res) => {
let target = guiUrl;
if (req.url.startsWith(apiPrefix)) {
req.url = req.url.replace(apiPrefix, '/');
target = apiUrl;
}
if (req.url.startsWith(fnApiPrefix)) {
req.url = req.url.replace(fnApiPrefix, '/');
target = fnApiUrl;
}
proxy.web(req, res, { target })
proxy.on('error', (error) => {
console.log(error.message)
res.end(maintenanceHtml);
})
}).listen(port, () => {
console.log(`Proxy server has started on port 80`)
});
I think that there is react server settings that I'm not able to find.
There is a little example that you're able to start at your own PC.
https://github.com/b2b-Alexander/react-js-problem
Found solution on github: https://github.com/vitejs/vite/discussions/7620
I got installed new v18.12.1 version of NodeJS.
My main machine has v16.14.0
So I rolled back the version of NodeJS for my project.

Permessage-Deflate Extension Breaks Socket.io WebSocket Communication (400 Bad Request)

I need to enable compression for websocket communication (using socketio). I did this by setting the perMessageDeflate to true which worked fine in my development environment and on a staging server (verified with Wireshark). However, on our production server the websocket connection fails and socketio (v4.4.1) falls back to polling. Both use nginx as a reverse proxy with the same configuration. Chromium console shows
WebSocket connection to
'wss://***/ws-test/socket.io/?EIO=4&transport=websocket&sid=9P4EelJhF0CcxvwNAAAE'
failed: Error during WebSocket handshake: Unexpected response code:
400
I created a minimal sample that shows the same behaviour. Nodejs app on the server:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
perMessageDeflate: true
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
server.listen(3001, () => {
console.log('listening on *:3001');
});
Client:
...
<script src="socket.io/socket.io.js"></script>
<script>
var socketio_path = window.location.pathname + 'socket.io';
var socket = io( { path: socketio_path } );
</script>
</body>
The error 400 seems to come from the nodejs server, not from nginx. I enabled all kinds of logging but couldn't find any related messages. Software versions are also reasonably close and up-to-date: nginx 1.18.0 on both (staging and production), nodejs 14.19.0/14.18.1 (staging/prod). Do you have any ideas that could help making this work on the production server?
It turned out, the issue is the Azure Application Gateway used on the production server. When it's bypassed, the websocket connection (with perMessageDeflate enabled) works fine.
Switching to a newer version of the Azure Application Gateway (v2 instead of v1) solved the issue in the end.

Having a problem securing an Express API with TLS

I have a REST API running on Node JS with Express.
I keep having issues with CORS because the front end is HTTPS and the backend API is HTTPS which frequently, but not always gets reported as a violation.
I am trying to secure the API with a Let's Encrypt cert but I seem to be missing something.
Here is the code that initializes the express server:
require('dotenv').config();
const https = require("https"),
fs = require("fs");
const app = require("./src/app");
const port = process.env.PORT || 8000;
https
.createServer(
{
key: fs.readFileSync('/etc/letsencrypt/live/myserver.com/privkey.pem', 'utf8'),
cert: fs.readFileSync('/etc/letsencrypt/live/myserver.com/fullchain.pem', 'utf8')
},
app
)
.listen(8000, function() {
console.log('HTTPS listening on PORT 8000');
});
Is there another approach? Or am I just doing it wrong?
CURL still works on HTTP which surprises me. There shouldn't be an HTTP server listening on 8000. GET calls work without the SSL configuration but POSTs always fail.
All the APIs work locally, it's just when I push it to production that it fails. But then, locally, it's not running HTTPS so there is no violation.
I haven't seen posts that address this specifically so I have to wonder what I'm missing. This has to be a common scenario.
Thanks for any help.
Try either of these solutions, whatever suits you:
import * as Cors from 'cors';
const cors = Cors( { origin: true } );
app.use( cors );
var cors = require('cors');
var app = express();
app.use(cors());

Tchat with NodeJS on port 1337 doesnt work (server on Debian)

Hello and sorry for my bad english, but I have a problem with my tchat created with NodeJS. My server.js running on port 1337 in my VPS, but with port isn't secure and i don't know how secure him.
All my website is secure with a Let's Encrypt certificate, but not the 1337 port...
I tried to secure https://www.temtem-france.com:1337/ with Let's encrypt but it doesn't work... :/
I have this on the beggining of my server.js :
var https = require('https'),
fs = require('fs'),
mysql = require('mysql');
var options = {
key: fs.readFileSync('/etc/letsencrypt/archive/temtem-france.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/archive/temtem-france.com/cert.pem'),
ca: fs.readFileSync('/etc/letsencrypt/archive/temtem-france.com/chain.pem'),
requestCert: false, rejectUnauthorized: false
};
var httpsServer = https.createServer(options, function (req, res) {
res.writeHead(200);
console.log('Affiché');
res.end("Hello World\n");
}).listen(1337);
With inspector on my client.php code, i have this :
socket.io.js:1 Failed to load resource: net::ERR_CERT_DATE_INVALID
client.js:31 Uncaught ReferenceError: io is not defined
at client.js:31
at HTMLDocument.<anonymous> (client.js:117)
at i (jquery-min.js:2)
at Object.fireWith [as resolveWith] (jquery-min.js:2)
at Function.ready (jquery-min.js:2)
at HTMLDocument.K (jquery-min.js:2)
Unchecked runtime.lastError: The message port closed before a response was received.
I already managed to run my codes, but it was several months ago and since I am not very comfortable with server management, I forgot how I had succeeded.
Thanks a lot if you can help me !

Resources