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

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.

Related

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 JS route continues to execute endlessly

I am new to Express JS and Node in general, and I am having a slight problem here that I don't understand its reason.
So basically, this is my code for index.js:
const express = require('express')
const app = express();
app.get('/', (req, res) => {
console.log("Continuous message!");
res.send("Hello World");
});
app.listen(3000, () => console.log('Example app listening on port 3000!')
)
Everything works great except for one thing. In my console the message "Continuous message!" keeps showing up endlessly in my console. Am I doing anything wrong here? Or is this the normal behavior here?
Thank you!
Update: the reason turned out to be the redirection from port 80 to port 3000. So I edited server's site-available and the repetition no longer occurs. Question is now, how do I configure my AWS EC2 server to redirect traffic from port 80 to port 3000 without previous problem?
Update: I tried the EC2 Load Balancer and iptables commands. The problem is still there. Console messages and route code continues to execute every like 5 seconds. Which causes problems with my code flow.

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.

pointing node.js app to my ip address and running locally

So I have two questions about the topic. I have purchased a VPS with digitalocean.com to host my node.js app and they gave me an example hello world app to start.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var html = "hello world";
res.end(html);
}).listen(8080, 'localhost');
console.log('Server running at http://localhost:8080/');
So this code works locally and when I host on the VPS I replace 'localhost' with the IP address of my VPS and it is available on the web when I go to http://IP_Address_of_VPS:8080
My first question: How do I host it live on the web but have it point to my IP address? When I replace 'localhost' with my IP address it does not work when I go to http://my_IP_Address:8080
My second question:
I made a test app following a node.js tutorial and here is the code
var PORT = process.env.PORT || 8080;
var express = require('express');
var app = express();
var http = require('http').Server(app);
app.use(express.static(__dirname + '/public'));
http.listen(PORT, function(){
console.log('listening on port *:'+PORT);
});
Where public is the folder with a simple html page. This app works when I run it locally at http://localhost:8080
Can someone explain how the second app runs locally when I did not specify 'localhost' in the http.listen() function? Also how do I point the second app to run from my IP address if the process is any different from the first?
First question
I hope I understood your question right, here is an attempt at an answer :)
Depends a bit on what you mean with 'my ip address'. If it is your public ip adress, you might have to set up port forwarding. Most routers will deny traffic from the outside network (which you are doing when connecting to your own public ip address) to the internal network by default.
If you mean a private ip address (local to the local network) you need to you use your public ip address and set up port fowarding.
When you set up port forwarding to your local machine you might also want to make your private ip address static.
However, I do not recommend using your home computer as a production server. You will need to solve a lot of problems like making your network secure and having low downtime.
Second question
When no hostname is passed to http.listen, the server will accept connections on all adresses. See documentation for more information.
This works, because when you omit arguments in a function call, they will default toundefined. For example, http.listen(8080) might appear as http.listen(8080, undefined, undefined, undefined). Inside the function body these will often be substituted with some default value.
The process of making your app available to the rest of the world should not be any different.

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

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.

Resources