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

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.

Related

Express.JS server to connect to host on remote network

So I got this small express server running. I can connect it to other devices on my local network e.g. mobile and other PC.
However when connecting over my 4g it does not work. Is there any reason for this? I am sure when I ping other private addresses on remote networks it has worked before, why not now?
Code:
const express = require("express");
const server = express();
const PORT = 3000
server.use(express.static("static"));
server.get("/", (req,res)=>{
res.sendFile(__dirname + "/pages/index.html")
});
server.listen(PORT, "0.0.0.0", (req,res) => {
console.log("Listening on port ", PORT)
});
Any information would be apricated I have some networking experience (still a noob just studying) and this really does interest me.
I assume you are trying to reach the server via your local IP. But you are doing it with 4G (in your phone maybe), which means your request is going over the internet while your local IP is only valid in your network.
Even if you are using your public IP, you would probably have to configure port forwarding on your router for it to know how to handle the incoming traffic for this port.
If you host your express server in your private network , you must have access to the express server by create port forwarding, destination nat, or some kind of publishing private services to public world methods.
If you need more help , i need to know more about your network env , your public ip and ...
Feel free to ask
An have a productive day

How to connect to node.js server from any ip

I want to create a private backend for an application I want to make, but I am having trouble connecting to my node server, I have the basic stuff right now,
var http = require("http");
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<html><body><h1>Hello World</h1></body></html>');
}).listen(3000);
console.log('Server running on port 300.')
But this only works for https://localhost:3000/, how do I make it so that if I have a separate computer on a separate connection, I can connect to this server?
I am not interested in just opening it to everyone but just to specific client IP's...
If the client IP's are on the same network as you, you can check out this question
If you want people from anywhere to access your application, I suggest hosting it on something like Heroku (very easy to deploy, pretty good free tier). You can then create a whitelist of IPs in your express application.
I would suggest for any port forwarding using ngrok or configuration in your router
For downloading ngrok https://ngrok.com/ go to this link
For configuration your router it will take some searching in google based on what type of router your using
You must mention that your localhost or Nat Ip and your public IP to resolve here is NOIP refrence https://www.noip.com/support/knowledgebase/general-port-forwarding-guide/
As you specified that you want the backend to be private, such that it can only be accessed by your specified node. You will have to host this node server on a cloud service or you can host it on your local machine by opening a port for the node server. Suppose you host the node server on port 1234 on your local machine ip address.
You can start the node server on localhost and your desired port, but you need to allow requests to the particular port.
Now you need to check for the origin of the request that your node server receives and validate that, so that only your private node(computer) can access the node server. You can do that by validating the hostname using express, you can get the hostname of the request in express.js using req.hostname or req.headers.host.
You would need to use express.js for this functionality and the code would be as follows
let express = require('express');
let app = express();
let allowedHost = 134.32.234.3 // the hostname which is allowed to access the backend
let port = 1234; // desired port
let host = 0.0.0.0 // desired host; 0.0.0.0 to host on your ip
app.get((req, res) => {
res.header('Content-Type', 'text/html');
if(req.hostname == allowedHost){
res.send('<html><body><h1>Hello World</h1></body></html>');
}
else{
res.send('Connection not allowed');
}
});
app.listen(host, port, ()=>{
console.log(`The server is running on http://${host}:${port}`);
}

how to create url in node.js project

i am trying to url in node.js project
currently show in my local server port like -http://localhost:1337
expected url =http://localhost:1337/nodeprovider
var http = require('http');
var port = process.env.port || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(port);
If I understood you right: you need your node.js server to response on http://abcwebsite
/nodeprovider
Since this that task must be done not in Node.js server I suggest you to read about domain parking: https://en.wikipedia.org/wiki/Domain_parking
Making long thing short: Node.js server is not responsible for domain name it responds on. Inside server script you can only set port to listen.
From an old answer
You dont assign a domain to a node.js server, instead you load your app onto a machine which has an ip adress. You then need to make sure your app is listening on the correct port, which on most servers is 80.
now getting a domain name to point to this ip adress is an entirely separate matter. You need to make your name server point to the ip. Your name server will usually be the company you bought the domain name through, for instance GoDaddy is a Domain Name Server (DNS). So if you had a domain name with them, you would go on their site under DNS settings and change the ip adress. Your domain name will then point to your ip adress and should render your node.js app.

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.

Hostname not working node.js

My code is as follows:
var http = require('http');
var static = require('node-static');
var file = new static.Server();
http.createServer(function (req, res) {
file.serve(req, res);
}).listen(1337, '127.0.0.1');
When the url is localhost:1337/1.html it works fine. However if I change it to hostname:1337/ where 'hostname' is the hostname of my server, I get unable to establish connection error. In PHP i could easily replace 127.0.0.1 or localhost with hostname. Why isn't the same possible in node.js?
So the problem is when your browser resolves "hostname", DNS gives it your local network IP address like 192.168.0.42, but your code tells node to listen on one and only one IP address: 127.0.0.1, so the connection doesn't work. Replace '127.0.0.1' in your node code with '0.0.0.0' (which means "all IP addresses") and things will work. Be advised that other computers on your local network (like other folks in a coffee shop wifi network) will be able to connect to your application, which is why for development sticking with the loopback IP address (127.0.0.1) and 'localhost' are better choices.

Resources