Express - public server - node.js

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.

Related

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.

Why do we need to manually set which port an Express app should listen to?

Was it always the case that once you generated an express application you have to set manually what port you'd like to listen to? I am just curious. It would make sense that right after I install the app I could just go ahead, start the app and it would automatically "be working" (as in I need to just navigate to my site)?
You can set which port to listen on in you app.js file, it's gonna run unless that port is busy, which can be handled by, setting which ports not to use in usual case, or configure your webserver to auto=start your app on server boot, which will reduces the possibility of the port being busy. or just edit your code to try random combinations until it finds a port.
Chosing Random Post For Your Server And Logging The Output In Console
As Joe Clay told you to use 0 instead of a port number it shall solve your problem, However if you wish to know details call function on server startup,
app.listen(0,'your_device_local_network_IP', () => {
console.log(app.address())
}
It will log out the details about your server, this should be the result if you use local network IP (I personally use it to check my site across multiple device in my network)
{ address: '192.168.10.5', family: 'IPv4', port: 34488 }
You do not enter your Local network IP, emit the 'your_device_local_network_IP' which is optional, the output should be like
{ address: '::', family: 'IPv6', port: 38135 }
Here is my simple working Server:
let http = require('http');
let path = require('path');
let serveStatic = require('serve-static');
let express = require('express');
let app = express();
app.set('views', './views');
app.set('view engine', 'pug');
app.use('/', serveStatic('./public'));
app.get('/', (req, res) => {res.render('index')});
let server = http.createServer(app);
server.listen(0, () => {
console.log(server.address())
})
How to set port for express server dynamically?

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.

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.

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