Run Node JS server without port number - node.js

Can we run our node application without specifying any port number. And if we can do that so what are the ways to achieve that.

You do need a port number. A "port" is basically a mapping that will allow the OS to forward the incoming network packets to a specific process. So a server with no port is useless (or not a server).
What you can do instead, in order to find a port dynamically, is to use a module like portfinder.
As an example you can do this:
const express = require('express')
const portfinder = require('portfinder');
const app = express()
app.get('/', (req, res) => {
res.json({ok: 1})
})
async function main() {
const port = await portfinder.getPortPromise()
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
}
main()

Related

How to run different server on same port?

I have created 2 server with express and node.js and now I want to run both the server on the same port which is localhost:8000 with different end points.
How it can be done or what can be the approach for it?
Attaching the server code for reference:-
Server1:-
const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;
app.get("/WeatherForcast", function (req, res) {
axios.get('https://localhost:7173/WeatherForecast')
.then(response => {
res.status(200).json({ success: true, data: response.data});
})
.catch(error => {
console.log(error);
});
});
app.listen(PORT, function () {
console.log(`Server is running on ${PORT}`);
});
Server2:-
const express = require("express");
const cors = require("cors");
const app = express();
const axios = require('axios');
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
const PORT = 8000;
app.get("/UserData", function (req, res) {
axios.get('https://localhost:7173/UserData')
.then(response => {
res.status(200).json({ success: true, data: response.data});
})
.catch(error => {
console.log(error);
});
});
app.listen(PORT, function () {
console.log(`Server is running on ${PORT}`);
});
Currently when I run it, one server runs and for other server an error is displayed that port 8000 is already in use.
You can't run two servers on the same port. The OS and TCP stack won't allow it.
The easiest solution is to use two endpoints on one server.
If you have to have two separate servers, then you would run them both on separate ports (neither of which is the public port) and then use something like nginx to proxy each separate path to the appropriate server.
So, the user's request goes to the proxy and the proxy examines the path of the request and then forwards it to one of your two servers based on the path of the request (as setup in the proxy configuration).
Two different servers can not be hosted on same port as it will give the error i.e "this port is currently is use" something like this.
The thing that can be done is instead of creating multiple server you can create a single server and define different endpoints to manage the code flow.
it is not possible to run different servers on same port

I am building container with node. but I can't connect app in container [duplicate]

This question already has answers here:
Containerized Node server inaccessible with server.listen(port, '127.0.0.1')
(2 answers)
Closed 8 months ago.
I am building container with node.
I have two type of codes. I think two codes very simple and similar. and package.json and Dockerfile is same. just different code.
but I can connect app in container. but the other one can't connect app in container.
This code is working well in container.
const express = require('express')
const PORT = 3000;
const app = express();
app.get('/',(req,res)=>{
res.send('Hello World');
});
app.listen(PORT);
console.log('Running');
but This code is not working What wrong with this? this is node official sample code.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
please tell me what problem is.
Thank you in advance
The sample code works when run on the host machine, but not when run in a container.
The issue is that the sample code binds to the 127.0.0.1 IP address. That means that it'll only accept connections from localhost.
In a container, localhost is the container itself. So when you try to connect from the docker host, it looks like the connection comes from another machine and the connection is rejected.
To fix it, you need to make it accept connections from outside the container. You can do that by changing the hostname variable to 0.0.0.0 like this
const http = require('http');
const hostname = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You can also leave out the hostname variable on the server.listen call as you've done in the first program. The default value is 0.0.0.0, so leaving it out also works.

How do I get user geo location from a node js(express) server?

I need to build a project to get user's country or location. With front-end user needs to give permission which could be bothersome for the API calls.
Is there any way to get an approximate location of the user from their IP address in node.js(express) server?
A solution could be to use APIs that return geoinformation for a given IP.
A sample could be this one which uses ip-api
const fetch = require('node-fetch')
const express = require('express')
const app = express()
const port = 3000
app.post('/location_specific_service', async (req, res) => {
var fetch_res = await fetch(`https://ipapi.co/${req.ip}/json/`);
var fetch_data = await res.json()
res.send(`You are from ${fetch_data.region}`)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

Can't get Hello World with Node.js in Cloud9

I can't figure out how to get my server to respond with Hello World.
I don't even know what IP address is. Is the ip listed on the tab of my terminal it?
I just created an EC2 environment with the default Node.js template.
Do I need to setup more things beforehand?
https://i.stack.imgur.com/4m85x.png
Try the solution bellow and let me know if you need any explanation:
const http = require("http");
const port = 3000; // make sure the port number is not used
const requestHandler = (req, res) => {
req.on('Error occurerd', (err) => {
console.error(err);
res.end();
});
res.end("Hello from AWS Cloud9!");
}
const server = http.createServer(requestHandler);
server.listen(port, () => {
console.log(`Server is listening on port ${port}!`);
// Run your script then copy past this url in your browser 127.0.0.1:3000
});

In Express JS does app.listen need to be at the end of the file?

In most tutorials using Express JS the app.listen function is always added at the end of the file. I want to understand if this is essential as all middleware is run in sequence.
Most examples show:
const express = require('express)
const app = express()
app.get('/', (req, res) => {
res.send('Test')
}
app.listen(3000, () => {
console.log('Server running on port 3000')
}
Is there any reason this shouldn't be done:
const express = require('express)
const app = express()
app.listen(3000, () => {
console.log('Server running on port 3000')
}
app.get('/', (req, res) => {
res.send('Test')
}
I worked out the answer to this, in case anyone goes looking for it.
app.listen is effectively a wrapper function that calls HTTP.createServer.
From what I can understand createServer sets up an event listener on the event loop. When the operating system receives a HTTP request on the particular port being listened to, such as port 80, the req is processed by express.
Since createServer is an asynchronous operation it gets executed in the event loop once the main program is executed. Therefore it doesn't matter where this code is placed. It is at the end in most examples as a standard rather than technical requirements.

Resources