Node.js server working fine on local but not on server - node.js

var express = require('express');
var app = express();
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
app.get('/getCode', function (req, res) {
res.send("hai");
})
the server starts successfully,but on calling the ip:3000/getCode doesn't give a response.
I have opened the port 3000,and am on aws ec2 ubuntu server

change source from custom ip to anywhere and 0.0.0.0. this will allow you to access that api from any IP address once you are sure this works you can change it to custom ip address to the ip address you want to access from.

try setting port like this:
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log('Example app listening on port:' + port);
});
Explanation: When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may at times independently configure the process.env.PORT variable for you.

Related

Why use a static port for express in dev environment but not in production?

Been looking around and multiple sources (i.e tutorials and examples) state that you start a server like this:
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
But when deploying you write like this below: (which is also stated by the deploy service "Setup Node.js App" which seems to be a common tool)
app.listen();
Naturally, I'd use something like below to combat this issue:
if (process.env.NODE_ENV == "prod") {
app.listen(0, () => {
console.log("prod");
});
} else {
app.listen(process.env.PORT, () => {
console.log(`Server is listening on port ${port}`);
});
}
But when testing the 'prod' environment on localhost the script compiles well but I get ECONNREFUSED in Postman. Why do I need to setup a port while on dev but I'm supposed to not set anything static in production? My own analysis on that is because of a best-practice method but since the deployment tool also warns about it and using no parameters in listen() fails - I get a bit unsure of why people are doing this.
When you are developing, a static port is nice because you always know where to reach it on your local machine. The only thing is that the port you specify must not be taken already.
When publishing to a cloud provider, you don't know what port the is should run on. Either the server lets Express choose it's own, or chooses a port that suits him best.
If you want to reach the prod version via Postman, you have to know the port chosen by Express. You can get it like this:
let server = app.listen(0, () => {
console.log(`Example app listening on port`, server.address().port);
});

Serving an Express js app to public internet from my personal laptop

I have a Node express Js App running in my local Network accessible at port 80.
Here is the express.cjs app
const express = require('express')
const app = express()
const port = 80
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Navigating to localhost:80/ I can see 'Hello World!' as expected.
I wanted to take this app to the internet serving it from my personal Laptop
Over the internet, I found port mapping will help me achieve this goal.
The following Steps were taken so far.
Port Forwarding.
Navigated to the default gateway address to enable port forwarding in the router. i.e 192.168.10.1
Router: WavLink
I added an entry to port forward incoming traffic as shown.
Uninstalled McAfee Antivirus Software.
Next, Navigated to Windows Defender Firewall with Advanced Security 
Created a new inbound port rule for port 80 to make sure that Windows Defender is not blocking the port.
Result:-
Then in my browser, I navigated to
http://61.68.**.**:80/   ( 61.68.**.** being my public IP ) 
I'm getting a page, as shown above, I'm not sure where I'm going wrong. Any pointers towards solving this issue will be very helpful.

one nodejs/express app only works on localhost, but not using IP address, another nodejs/express app works just fine?

I have a super simple Hello World app that I got to run on myipaddress:3000 instead of just localhost:3000 by doing:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
http = require("http");
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function(req, res) {
res.render("home.ejs");
});
app.listen(3000, "0.0.0.0", function() {
console.log('Server running on port 3000');
});
but i have another, more involved node.js/express app that also uses mongoDB/mongoose where when I change the app.listen to include "0.0.0.0", it still only runs on localhost:3000. I'm not sure what could be causing this, maybe something to do with mongoDB? that's the only real difference between that apps that I can think of that would make a difference. I'm not running them both on port 3000 at the same time. I also tested the Hello World with a different port and it worked fine, but the other app did not.
Does anyone know what else could be the issue here? Let me know if you need to see any other code.
As I know 0.0.0.0 is given as a host to access from the outside interface. And If you don't specify the host while calling app.listen() The server will run on all available interface ie. on 0.0.0.0 but you can bind the IP address like
app.listen(3000, '127.0.0.1', function(){
console.log('Server running on port 3000');
});

Express - public server

Use Ubuntu
Have Express app with Hello world. I wanna run app as public, setup static ip like in this video. It is my express server app:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var listener = app.listen(3000, function () {
console.log('Example app listening on port 3000!');
console.log(listener.address());// { address: '::', family: 'IPv6', port: 3000 }
});
I check my inet address with ifconfig command and get 192.168.0.102 - it is local IP address and when I enter 192.168.0.102:3000 I get Hello world. But when I try 194.242.103.139:3000 didn't have success. I am new with this stuff, please help and if you can with more details.
Thanks.
Assuming 194.242.103.139 is your public IP address, make sure you have enabled route (port forwarding) on your router/gateway/firewall. Or put your machine IP to DMZ.
Important If you don't know what DMZ or port forwarding or anything mentioned above is, or what security risks this brings, please, don't mess up with your router. You would be asking for a nasty surprise. Read something on the topic of networking and security first.

learning node express, why console does not output 'localhost'?

I am learning to use express and node in general and I realise that I could be missing many fundamental knowledge. Below is the code for starting a server to serve static files, and as i understand the console should output the server address and port number on startup.
var express = require('express');
var app = express();
app.use(express.static('resources'));
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("Server listening at http://%s:%s", host, port)
})
I am expecting to see 'Server listening at http://localhost:3000"' but instead i get: 'Server listening at http://:::3000'
Can anyone explain what this means please
thanks
See the documentation on net.Server::address().
It probably doesn't say localhost because you didn't specify what address you were listening for.
By default, there is no specific address because it will accept incoming requests on the port regardless of the address it was sent to.
Examples of various addresses it could accept are localhost, 127.0.0.1, 192.168.1.72 or if you port-forward your server through your network, it could be your global IP address. If you explicitly specify an address, it will reject incoming requests from all these other addresses.
Sounds like the perils of asynchronous execution of code. You are defining the host and port and immediately calling them in the console log statement. NodeJS is executing the log statement before initializing. Try printing the log statement outside the app.listen function.

Resources