I have nodejs running on pm2 and its listening on port 5000. If i run netstat -na |grep 5000 on the server i get
tcp 0 0 0.0.0.0:5000 0.0.0.0:* LISTEN
But when my react app makes a call to http://localhost:5000/patients i get
::ERR_CONNECTION_REFUSED
Here is the code for the server:
const app = express();
const port = process.env.PORT || 5000;
app.use('/patients', require("./routes/patientRoute"));
app.listen(port, "0.0.0.0", () => {
console.log(`server is running on port: ${port}`);
})
and from React production build i run GET with axios to http://localhost:5000/patients thats when the err occurs
Also i have opened the port on firewalld
first i had to get rid of the "0.0.0.0", then i replaced http://localhost:5000 with /api/ on all of my axios calls and then in my nginx conf file i needed to add location
/api/ { proxy_pass http://127.0.0.1:5000; }
.....the location block in NGINX was the key!
Related
Could not connect to localhost:3000
17:02:53
Error: Unexpected server response: 404
Handshake Details
Request URL: http://localhost:3000/socket.io/?EIO=3&transport=websocket
Request Method: GET
Status Code: 404 Not Found
My express server listen on 3000 port and socketio http on 443 port, i am able to connect socket by hosting this on ec2 instance and using ec2 ip with port number on postman socket connection ui, but on localhost connection always failed with above error on postman socket beta ui.
You need to call listen only once. If you pass your http/https server to express, app.listen() is enough. (except you want to listen on 2 different ports.. For testing, let's call it only once.)
For accessing it on localhost try setting it explicitly with the parameter hostname in app.listen().
Example:
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
// Let's only call listen once for testing purposes. If you call
// listen on the express app, your https server will automatically listen
// to the same configuration.
// httpsServer.listen(4000);
const port = 3000
const hostname = 'localhost'
// explicitly let the app listen on localhost. If hostname is not
// provided, it will take the first found ipv4 interface
app.listen(port, hostname, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on https://${hostname}:${port} 🛡️
################################################
`);
});
}
Now you should be able to connect your socket. If it still does not work try
to use http module instead of https for better isolating your problem.
Note that your server now only will be accessible using localhost and not over ip. Both may only be possible when running 2 server instances with different hostnames.
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
httpsServer.listen(443);
app.listen(config.port, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on port: ${config.port} 🛡️
################################################
`);
});
}
This is my app.ts file, I am using Ubuntu. so 443 port is not allowed, i changed this port to 4000, now the app listen on the 3000 and socket http server on 4000, but socketio not able to connect with socket url localhost:3000
I have a React app where I specified the port number in server.js as
const port = process.argv[3] || 3500;
At the bottom of the same file I wrote:
app.listen(port, () => console.log(`Web service running on port ${port}`));
While the app is able to run in my browser, unfortunately in the console of my text editor it says Web service running on port 3500 even when the url says localhost:3000.
I know that React uses port 3000 as default... but don't know why the app chose to use port 3000 instead of the port 3500 that I specified above.
To try and fix this I tried to install the dev dependency cross-env and in my package.json "start" script I specified cross-env PORT=3500.
After that change, I see that my React app is now running in the browser on Port 3500... but I am unable to avoid the message from the server.js file that says "Web service running on the Port # that I specified in the server.js file".
In server.js when I use const port = process.argv[3] || 3500; in conjunction with the cross-env port 3500 change in package.json... I get the message "Something is already running on Port 3500". So it seems impossible to get the correct console message that the React app is really running properly in the browser on Port 3500.
Full Express server.js below:
const jsonServer = require("json-server");
const chokidar = require("chokidar");
const cors = require("cors");
const fileName = process.argv[2] || "./data.js";
const port = process.argv[3] || 3500;
let router = undefined;
const app = express();
const createServer = () => {
delete require.cache[require.resolve(fileName)];
setTimeout(() => {
router = jsonServer.router(fileName.endsWith(".js")
? require(fileName)() : fileName)
}, 100)
}
createServer();
app.use(cors());
app.use(jsonServer.bodyParser)
app.use("/api", (req, resp, next) => router(req, resp, next));
chokidar.watch(fileName).on("change", () => {
console.log("Reloading web service data...");
createServer()
console.log("Reloading web service data complete.");
});
app.listen(port, () => console.log(`Web service running on port ${port}`));```
Express Server:
you can run express server in the any port you want it to run
const port = process.env.port || 4000 //? can be any port number
the console log you are getting in the editor is from the server and not from the react app.
React App:
by default react app runs in port 3000 if you want to change the Port of the react app then use react-scripts like this
"start": "set PORT= <Your Desired Port> && react-scripts start"
or you can set port directly from terminal like this
PORT=4000 npm start //? or any other port number
app.listen is for express servers. To run a react server use react-scripts. To change port number use the PORT environment variable.
I've two node.js servers: one is http, and the other is https
//HTTP server
http.createServer(function(request,response){
unifiedServer(request,response);
}).listen(config.httpPort,function(){
console.log('listening at port ' + config.httpPort)
});
//HTTPS server
var httpsServerOptions = {
'key': fs.readFileSync('./https/key.pem'),
'cert': fs.readFileSync('./https/cert.pem')
};
https.createServer(httpsServerOptions,function(request,response){
unifiedServer(request,response);
}).listen(config.httpsPort,function(){
console.log('listening at port ' + config.httpsPort)
});
//Instantiating the servers
var unifiedServer = function(request,response){....
When I run it, it will console.log listening at port 3000 (http) and listening at port 3001 (https)
3000 works just fine but.. When going into 3001 I get This page isn’t working
I've checked in case the key and certifications might be the problem, but as far as I can see they are doing their work just fine.
Any insights into this problem are appreciated
You need https on the URL to the 3001 server:
https://localhost:3001/home
Here's the app.js, the code is too long so that's why I'm showing this code only, there's no problem in other code I assume this is a network problem.
app.js
app.listen(8080, 'localhost', function () {
console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});
I don't get any response when i run lsof -i :8080. but I do get response when I run curl localhost:8080 on the server.
and I don't think there's any problem with security group. I allowed any ip to access to the instance as you can see below.
and here's actually how it looks like when I test public ip and localhost
ubuntu#:ip~/$ curl -v 18.217.107.76:8080
* Rebuilt URL to: 18.217.107.76:8080/
* Trying 18.217.107.76...
* connect to 18.217.107.76 port 8080 failed: Connection refused
* Failed to connect to 18.217.107.76 port 8080: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 18.217.107.76 port 8080: Connection refused
ubuntu#ip:~/$ curl -v localhost:8080
I get response here!
I changed the code from
app.listen(8080, 'localhost', function () {
console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});
to
app.listen(8080, function () {
console.log('Express started on http://localhost:' + 8080 + '; press Ctrl-C to terminate.');
});
now it's working
This is what worked for me!!
In your security group you have added the rule HTTP which listens by default on port 80.
So basically if you have configured your node server to run on a port other than port number 80 (I was doing this mistake) and try to access the public DNS(EC2 public DNS can be found in instance description) on browser, connection refused error might come so what you can do is change the PORT value in the config to 80.
Your config.env will look like this
PORT=80
And in your server.js you can write
const PORT = process.env.PORT;
try {
app.listen(PORT, () => { console.log(`server running at port ${PORT}`) })
} catch (error) {
console.log(error)
}
I spend 1 day to search all on google and try all the code but it seem like nothing work.
My server code.
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
I try to replace 3000 by 80 but not work.
I also try to change in etc/nginx/conf/example.com.cof
server {
listen 80;
upstream project {
server example.com:3000;
}
server {
listen 80;
location / {
proxy_pass http://project;
}
server_name example.com;
rewrite ^(.*) http://example.com$1 permanent;
}
server {
listen 80 default_server;
...
}
Nothing work.
Please help
using port 80 requires sudo privileges
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
Start app using,
sudo PORT=80 node app.js
sudo PORT=80 npm start #or like this, depends on your app