Hostname not working node.js - 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.

Related

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.

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 can't access to server from internet

hi first of all I have limited knowledge of network.
operating system is mac, firewall is turned off.
it works on a local network: http://192.168.1.2:8080 (add to safari)
next I got my ip address from google.com "what is my ip"
78.157.xx.xxx, so I tried from internet connect to server like:
http://78.157.xx.xxx:8080 (add to safari), but with no success :(
I have a router and 3 devices, and all these three devices have the same ip 78.157.xx.xxx?
server.js
var http = require('http');
http.createServer(function (req, res)
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
})
.listen(8080, "0.0.0.0");
You need an open port on your router to allow a connection in to your home network from the Internet. Then you need to create a port forward from 78.157.xx.xxx:8080 to 192.168.1.2:8080.
You can get more details about port forwarding here.
Here is a useful guide and resource to configure the router.

Allow Public IP to connect via WebSockets

I tried to creating a chat with nodejs ws (einaros),this is my code:
Server:
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 80 });
wss.on('connection', function(ws) {
console.log('connecting count:' + wss.clients.length);
});
Client:
var hostname = location.hostname;
var port = 80;
var url = 'ws://'+hostname+':'+port+'/';
window.WebSocket = window.WebSocket || window.MozWebSocket;
var w = new WebSocket(url);
when I test with my computer or some other computers who connect with my router, it works well. However, other clients who visit via Internet cannot make the connection. Of course, they use the public IP, like 218.xxx.xxx.xxx, not 192.168.xxx.xxx.
I wonder how to solve this problem.
Thank you for you answer. But, it may be not the NAT problem. For example, My public IP is 218.100.50.50,and My private Ip is 192.168.1.1. When a connection comes from outside my network and visits 218.100.50.50:80, the router will redirect it to 192.168.1.1:80. There's a web page which can be visited in this way, but still cannot make the connection to my websocket server. This problem really confuses me much.
Sitting behind router with IPv4 leads to problems for routing actual traffic to right direction (computer behind router).
You need to Forward port 80 in router settings to your computer IP. Additionally I would recommend set in router settings preferred IP for your computer so after restart it is more likely not to change local IP address (otherwise can happen).
After those changes, you can even try to connect using Public IP from your own computer, and if it will work - then it should work from external computers.
Additionally check firewall settings to make sure it does not blocks any external traffic to port 80.
Your problem is called NAT: http://en.wikipedia.org/wiki/Network_address_translation
When a connection comes from outside your network (that is, against your public IP), the router doesn't know who's going to receive that connection. Imagine there are 3 PCs and 2 smartphones connected to your router, which one is going to "answer"? Well, what you have to do is tell the router: "dear router, when my friends try to connect on port 80, redirect them to device 192.168.1.37 and port 80 (for example)".
And if you don't want to reconfigure your router again and again to update 192.168.1.37 (because of DHCP random IP assignation) then tell your router to assign the same IP to your PC always (static ip).
So, configure a "static IP" for your PC, and create a port forwarding rule for port 80 to redirect traffic to your server. You can search "server behind router configuration" for more details, there are thousands of tutorials.

Resources