How to use app.listen(port, host) with public hostname? - node.js

Can I put public domain name as host argument in app.listen(port, host)?
I know my ip, and I have 3 domain names on this ip. domain1.com, domain2.com all on same ip. Now, I'm using switch in app.get('/') to routing request of different domain names. However, I'm wondering is there a way to route host when setting up app.listen.
I found the entry of app.listen([port[, host[, backlog]]][, callback]) is really vague on expressjs website. There's nothing about the "host" argument. I know it can be set to localhost or 127.0.0.1. But my code failed when I put public domain name in it.
Can anybody explain how the host argument works in app.listen? Thank you.
var express = require('express');
var app = express();
app.get('/', function(req, res) {res.send("hello")});
app.listen(3000, "my.domain");
Error code:
Error: listen EADDRNOTAVAIL: address not available myip:3000
at Server.setupListenHandle [as _listen2] (net.js:1281:19)
at listenInCluster (net.js:1346:12)
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1485:7)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:65:10)
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1325:8)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
code: 'EADDRNOTAVAIL',
errno: 'EADDRNOTAVAIL',
syscall: 'listen',
address: 'myip',
port: 3000
}
The server can't run.

Try to start server with hostname 0.0.0.0 and get access from other network points by your IP (check by ifconfig).

Find out the public ip of your public domain, then put it in the app.listen.
Example if your public ip is 1.2.3.4:
app.listen(3000,'1.2.3.4');

Related

Can't start Vite dev server on 443 without root, but native node server on 443 works without root

I was trying to use vite in my project and wanted to start the local dev server on 443 port (MacOS) and I'm presented with the following error:
error when starting dev server:
Error: listen EACCES: permission denied 127.0.0.1:443
at Server.setupListenHandle [as _listen2] (node:net:1415:21)
at listenInCluster (node:net:1480:12)
at GetAddrInfoReqWrap.doListen [as callback] (node:net:1629:7)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:111:8)
Now as per *nix systems, I should get this error as ports < 1024 need root access.
But my question is, how am I then able to listen on 443 port on a native node server?
const http = require('http');
const requestListener = function (req, res) {
res.writeHead(200);
res.end('Hello, World!');
}
const server = http.createServer(requestListener);
server.listen(443);
The code above works without any issue (also works with https module) on my system and without root access.
Can someone explain what is happening?

PM2 listening on port 443 shows EADDRINUSE: address already in use :::443

I have a Node/Express server running on an AWS Lightsail instance with PM2 as a process manager. The server is currently listening on port 4000. The IP address for the instance is attached to a subdomain that has a valid SSL certificate and automatically redirects from HTTP to HTTPS. Visiting https://example.com at the moment shows the 'Congratulations! You are now running Bitnami Node.js 12.18.3 in the Cloud." page.
Currently, all the Express endpoints are only accessible through http://example.com:4000/endpoint, but I want the Express app to run on port 443 so that the endpoints are accessible immediately on https://example.com/endpoint.
I read that PM2 is able to listen on ports 80 and 443 and tried the method mentioned in the documentation, but whenever I change the port number in the .env file to 443 and reload the app using pm2 reload app, I get the following error:
0|app | Error: listen EADDRINUSE: address already in use :::443
0|app | at Server.setupListenHandle [as _listen2] (net.js:1313:16)
0|app | at listenInCluster (net.js:1361:12)
0|app | at Server.listen (net.js:1447:7)
0|app | at Function.listen (/opt/bitnami/apache/htdocs/node_modules/express/lib/application.js:618:24)
0|app | at Object.<anonymous> (/opt/bitnami/apache/htdocs/app.js:44:5)
0|app | at Module._compile (internal/modules/cjs/loader.js:1137:30)
0|app | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
0|app | at Module.load (internal/modules/cjs/loader.js:985:32)
0|app | at Function.Module._load (internal/modules/cjs/loader.js:878:14)
0|app | at Object.<anonymous> (/opt/bitnami/node/lib/node_modules/pm2/lib/ProcessContainerFork.js:33:23) {
0|app | code: 'EADDRINUSE',
0|app | errno: 'EADDRINUSE',
0|app | syscall: 'listen',
0|app | address: '::',
0|app | port: 443
0|app | }
App.js
const express = require('express');
const dotenv = require('dotenv');
const app = express();
app.use(express.json()); // for parsing POST bodies
dotenv.config();
app.get("/hello", (req, res) => res.send("Hello World!"));
app.listen(process.env.PORT, () => {
console.log(`🥁 App listening on port ${process.env.PORT}!`);
});
.env
PORT=443
Edit:
pm2 status output
Unfortunately I wasn't able to use Nginx, but instead used Apache's virtual hosts config to redirect all traffic from ports 443 to 4000. More info here.
you console error stats port is already being used, give a try changing PORT=8282 and see if this solves, however, if the problem still persists then move your dotenv configuration at the top require('dotenv').config().

NodeJS - Error: listen EADDRNOTAVAIL: address not available

I am running a Node app that should be hosted on a local server.
At the moment, I am sending just a plaintext response.
const http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {ContentType: 'text/plain'});
res.end("test");
});
When I listen to the localhost everything works fine and I am able to send the request from my browser.
server.listen(3000, '127.0.0.1'); // works fine, on the same machine
However, if I try to listen to a port on my LAN network by typing the router's IP, I get an error.
server.listen(3000, '192.168.0.1'); // causes an error
Error: listen EADDRNOTAVAIL: address not available 192.168.0.1:3
000
at Server.setupListenHandle [as _listen2] (net.js:1253:19)
at listenInCluster (net.js:1318:12)
at doListen (net.js:1451:7)
at process._tickCallback (internal/process/next_tick.js:63:1
9)
at Function.Module.runMain (internal/modules/cjs/loader.js:7
57:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Emitted 'error' event at:
at emitErrorNT (net.js:1297:8)
at process._tickCallback (internal/process/next_tick.js:63:1
9)
[... lines matching original stack trace ...]
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
I have tried this with my public IP address unsuccessfully.
Is there any way to listen to a port on a LAN server so that I can send requests from any computer on the network?
Also, I would later like my application to run on any computer on any LAN network. How can I dynamically add my host?
Try this
server.listen(3000, '0.0.0.0');
you can access your node application from other machine
e.g
your lan ip is 192.168.0.101 then you can browse 192.168.0.101:3000 from other machine
I got this error, the issue was I had a VPN connected
Be careful with your IP.
Sometimes it changes. When I work with Node I have to check the ipconfig in Shell... I hope with that it could help if someone else have the same problem...
The right IP address actually turned out to be 192.168.0.104.
The IP address of a server machine should be used, not that of a router.

Node.js http server crashes with unknown IP address displayed

I am running a Node.js HTTP server, and suddenly the following message is displayed, and the server crashes:
UPDATED ERROR LOG: (after edit)
Uncaught exception in main server
{ Error: connect ETIMEDOUT 139.99.8.126:80
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '139.99.8.126',
port: 80 }
Uncaught exception in main server
{ Error: socket hang up
at createHangUpError (_http_client.js:253:15)
at Socket.socketCloseListener (_http_client.js:285:23)
at emitOne (events.js:101:20)
at Socket.emit (events.js:188:7)
at TCP._handle.close [as _onclose] (net.js:497:12) code: 'ECONNRESET' }
This is a foreign IP address not used by us.
I tried to grep into all node modules for this IP address and see nothing.
Appears to be a hacking attempt but I have no clue where to start looking.
Any help will be appreciated. I have blocked the IP address in the firewall.
As per node.js docs about errors say:
ETIMEDOUT (Operation timed out): A connect or send request failed because the connected party did not properly respond after a period of time. Usually encountered by http or net — often a sign that a socket.end() was not properly called.
You should create a handler for errors, so your server won't crash:
netSv.on('error', function (error) {
if( error.message.code === 'ETIMEDOUT' ){
// mail the error with some additional data to you or do something with it
}
})

How do I access other IPv6 Adresses from my vps

Hello StackOverflow!
I recently bought a VPS, where I was given 64 IPv6 addresses, however I find myself unable to use any of them except :1. The IPv6 gateway looks like this (masked with x for security reasons) xxxx:xxxx:x:xxx::a where a is 1 to 64, I should have all of them available to my service, I'm just not able to use any of them except 1. It says that 1 is automatically assigned to the OS installed on my VPS, does that mean I have to assign the rest of the addresses as well? If so, how do I do that?
Here's the code I used in Node.js to try this.
const Express = require("express");
const App = Express();
App.use(Express.static(__dirname+"/www"));
const Listener = App.listen(1024, "xxxx:xxxx:x:x:xx::2", () => {
const addr = Listener.address();
console.log("Listening on " + addr.address + ":" + addr.port);
});
The error that I get when I'm starting it is:
Error: listen EADDRNOTAVAIL xxxxx:xxxx:x:x:xx::2:1024
at Server.setupListenHandle [as _listen2] (net.js:1318:19)
at listenInCluster (net.js:1383:12)
at doListen (net.js:1509:7)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
at startup (internal/bootstrap/node.js:236:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)
Emitted 'error' event at:
at emitErrorNT (net.js:1362:8)
at process._tickCallback (internal/process/next_tick.js:63:19)
[... lines matching original stack trace ...]
at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3)
Hello!
I managed to resolve this on my own after finding the right keywords to google for with the help of #Paul
The solution was to add each address to the interfaces file.
I used the command:
sudo ifconfig eth0 inet6 add xxxx:xxxx:x:x:xx::a/64

Resources