Server not working on any port except process.env.PORT? - node.js

How can i find the server port number ?
I have following code in server
var app = require('express')();
//creating http server
var server = require('http').createServer(app);
var port = process.env.PORT;
server.listen(port);
app.get('/testUrl', function (req, res) {
console.log(server.address());
console.log(server.address().address);
console.log(server.address().port);
res.end("working " + port);
});
I want to know the port number where node server is running (added consoles in request) I am getting following information using consoles at request
\.\pipe\5e2xxxxxxxxxxxxxxxxxxxxxxxx
undefined
undefined
Server returns following error If I change the server listening port to any other port except process.env.PORT
iisnode encountered an error when processing the request.
HRESULT: 0x2
HTTP status: 500
HTTP subStatus: 1001
HTTP reason: Internal Server Error

The issue in code , your are not defining default port.for set your default port you have to do like this.
var port = process.env.PORT || '';//put your default port here in ''.
and set your PORT in env
export PORT="your port number"(in terminal)

Related

use proxy pass xampp for socket.io node js server

I been trying to open the website from my mobile. I made two servers. One using xampp and php to run the website and get data from database. The second server is for running web socket. Real time chat and drawing. So server1 is in port 3000 and server2 is in 8000. how can I open both server in my mobile?
I tried
I put this in httpd.conf:
ProxyPass /node http://localhost:8000
and then in the client side, I put:
var socket = io('http://localhost/node', { transports : ['websocket']});
I am getting error:
WebSocket connection to 'ws://localhost/socket.io/?EIO=4&transport=websocket' failed:
node js setup:
const http = require('http');
const socket = require('socket.io');
const port = process.env.PORT || "8000";
const server = http.createServer((req,res)=>{
res.end('I am connected!');
});
const io = socket(server);
io.on('connection',(socket,req)=>{
socket.emit('Welcome','Welcome to the websocket server!!');
});
server.listen(port);
xampp setup:
$login = new Login();
$user_data = $login->check_login($_SESSION['Trial_User_Id']);
[xampp window][1]

APP Engine listening to Port 3000 giving 502 Bad Gateway error

I am new to node.js coding. I am learning to build a app I want to host on GCP App engine.
I have created a Node.js code which has hard requirement to listen to port 3000.
const dotenv = require('dotenv').config();
const express = require('express');
const app = express();
const crypto = require('crypto');
const cookie = require('cookie');
const nonce = require('nonce')();
const querystring = require('querystring');
const request = require('request-promise');
const { Console } = require('console');
// const PORT = process.env.PORT || 3000;
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello App Engine!');
});
On Yaml file I have specifically added ports to forward.
network:
forwarded_ports:
- 3000/tcp
unless I dont use 8080 port, app engine is failing with 502 Bad Gateway.
Is there a way I can use Port 3000 in App engine.
It works if I change the Port to 8080. But I want this to be at 3000.
I created firewall rules
enter image description here
Nope, you cannot change the default port in GAE.
The forwarded_ports is intended to open access to other services listening on other ports but always there should be something listening on the port 8080.
You can create a dummy service listening in port 8080 and possibly redirect to your app in port 3000. Something else to keep in mind is that when accessing the desired service in port 3000 or any other, this should be specified in the url like https://PROJECT_ID.REGION_ID.r.appspot.com:3000 or more general https://PROJECT_ID.REGION_ID.r.appspot.com:PORT

Deploying Node.JS express API App to Azure App Service

I'm trying to deploy my Node.JS app to Azure App Service. I followed this introduction: https://learn.microsoft.com/de-de/azure/app-service/app-service-web-get-started-nodejs.
Here is the code of my app:
var express = require('express'); // Web Framework
var app = express();
var sql = require('mssql'); // MS Sql Server client
const { request } = require('http');
// Connection string parameters.
var sqlConfig = {
user: 'username',
password: 'password',
server: 'serveraddress',
database: 'databasename'
}
// Start server and listen on http://localhost:80/
var server = app.listen(80, function () {
var host = server.address().address
var port = server.address().port
console.log("app listening at http://%s:%s", host, port)
});
app.get('/tags', function (req, res) {
sql.connect(sqlConfig, function() {
var request = new sql.Request();
request.query('select * from dbo.Tag', function(err, recordset) {
if(err) console.log(err);
res.end(JSON.stringify(recordset)); // Result in JSON format
});
});
})
The app runs locally without any problems. Simple testing in browser by typing localhost:80/tags returns all tags as json.
But after deployment to Azure this error occurs:
2020-06-25T17:11:58.055Z ERROR - Container wearxapplication_0_ed215082 for site wearapplication did not start within expected time limit. Elapsed time = 230.0801107 sec
2020-06-25T17:11:58.074Z ERROR - Container wearxapplication_0_ed215082 didn't respond to HTTP pings on port: 8080, failing site start. See container logs for debugging.
2020-06-25T17:11:58.088Z INFO - Stopping site wearxapplication because it failed during startup.
What its mean? How solve it?
Looking at the errors, I believe you are using App Service on Linux with Single container configuration. If so, do not explicitly listen on port 80 or any other (unless you are deploying via custom container where you would have control of the docker file). Behind the scene, app service on Linux deploys a container and expose an auto-detected port (docker expose). Your explicit listening port is unlikely to match that auto-detected port. Replace you server bootstrap code with below snippet to let the port get picked up from environment:
// Start server and listen on http://localhost:port/ for local
const port = process.env.PORT || 1337; // for local debugging choose any available port
var server = app.listen(port, function () {
var host = server.address().address;
console.log("app listening at http://%s:%s", host, port);
});
One more thing to check is whether any of the dependencies (express, mssql in your case) failed to resolve at startup. This can happen when you have the dependency missing in node_modules folder. You can check that by starting Log Stream (you can find in Azure portal app service blade). You might see error like this
Log stream

node.js https server not loading responding

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

Node.js + Express.js + Socket.io on port 443 (HTTPS TLS/SSL)

I have an app with Node.js, Express.js, and Socket.io that runs fine using ANY port except 443. The server is meant to only operate over HTTPS port 443 and likewise, the websocket should be encrypted as well.
CODE THAT WORKS
var fs = require('fs');
var https = require('https');
var express = require('express');
var socket = require('socket.io');
var sslOptions = {
key: fs.readFileSync(__dirname + '/../ssl/server.key,
cert: fs.readFileSync(__dirname + '/../ssl/server.pem,
ciphers: 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM',
honorCipherOrder: true
};
var app = express();
var server = https.createServer(sslOptions, app);
var io = socket.listen(server, {
"log level" : 3,
"match origin protocol" : true,
"transports" : ['websocket']
});
server.listen(8443);
When I change the port (last line) to 443, the Node server crashes right away with an error:
warn: error raised: Error: listen EADDRINUSE
Apparently you've already got a server listening on that port on your machine. Is is possible that you started this server elsewhere and it's still running?
It means that the port is in use, you can check using :
sudo netstat -tapen | grep ":443".
If you use Apache, Ngnix or other server it is likely to be it.

Resources