unable to run server, I think it is because I have 2 applications using the same port? - express

Just Curious (I solved this problem by just using a different port but the issue still triggers me), When I am trying to run the following code:
const app = express();
app.use(bodyParser.json({ limit: "30mb", exteded: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
const CONNECTION_URL = <correct MongoDB connection url>
const PORT = process.env.PORT || 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() =>
app.listen(PORT, () => console.log(`Server running on port`+PORT))
).catch((error) => console.log(error.message));
I keep getting an error thrown in my console:
{ code: 'EADDRINUSE', errno: -48, syscall: 'listen', address: '::', port: 5000 }
so after surfing through countless numbers of resources, they all essentially said I had to applications using the same port 5000? So I followed the "solutions" to the problem which all seemed to be killing the Port.
Firstly, I ran:
netstat -avtn | egrep 'Proto|5000'
To get:
Foreign Address (state) rhiwat shiwat pid epid state options
tcp6 0 0 *.5000 *.* LISTEN 131072 131072 1883 0 0x0100 0x00000006
tcp4 0 0 *.5000 *.* LISTEN 131072 131072 1883 0 0x0100 0x00000006
then I tried a few different commands to try and kill.
1) kill -9 $(lsof -t -i:5000)
2) kill <the appropriate pid>
3) kill -9 <the appropriate pid>
However, none of the solutions seemed to work. I even tried the famous computer off and on solution and closed all my applictions but they didn't work either. Does anyone know how I could have solved this without changing my port number?

Two different applications/processes cannot run on the same port. You will need to use different ports to use them parallelly.
Based on your OS there are tons of resources online to kill a process running on a specific port. The process/commands are similar to the ones you have listed to kill a process on a port.

Related

Cannot find host name for ElephantSQL server

I've been trying to set up an express server. All my routes seem to work correctly, it's connecting to the database that's giving me issues. I'm not great at backend but I feel like getting the host name shouldn't give me this many problems.
Here's my error: (batyr.db.elephantsql.com is my DB_HOST name):
Error: getaddrinfo ENOTFOUND 'batyr.db.elephantsql.com';
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: "'batyr.db.elephantsql.com';"
}
Here's my repository
Here's my knexfile.js:
require('dotenv').config();
const path = require("path");
module.exports = {
development: {
client: 'pg',
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
},
charset: 'utf8',
pool: { min: 1, max: 5 },
migrations: {
directory: path.join(__dirname, "src", "db", "migrations"),
},
},
};
Here's my .env file:
DATABASE_URL = 'postgres://pausapcx:vxSa5l3ZK_F2lrlMGhyt0XBlYbX7hfWY#batyr.db.elephantsql.com/pausapcx';
DB_HOST = 'batyr.db.elephantsql.com';
DB_USERNAME = 'pausapcx';
DB_PASSWORD = '***'; // cut just for this post
DB_NAME = 'pausapcx';
My server.js is running on port 8080, pgAdmin is running on port 5432
Here are the host and server names from elephantsql:
(https://i.stack.imgur.com/CnGQ4.png)
(https://i.stack.imgur.com/EVRkP.png)
I've tried with several differnet host names:
batyr.db.elephantsql.com (pgAdmin accepted this one)
batyr
I've tried the database URL
I've even tried just Elephantsql.com
I've pinged batyr.db.elephantsql.com in the terminal and gotten this response:
Pinging ec2-3-89-203-254.compute-1.amazonaws.com [3.89.203.254] with 32 bytes of data:
Reply from 3.89.203.254: bytes=32 time=41ms TTL=44
Reply from 3.89.203.254: bytes=32 time=76ms TTL=44
Reply from 3.89.203.254: bytes=32 time=38ms TTL=44
Reply from 3.89.203.254: bytes=32 time=37ms TTL=44
Ping statistics for 3.89.203.254:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 37ms, Maximum = 76ms, Average = 48ms
I really suck at backend, I'd appreciate any help.
Was able to get data!
terminal screenshot
The solution was to just swap out all the random connection data with a single database URL (I'll secure it in .env once it's all working)
// works:
connection: 'postgres://pausapcx:***#batyr.db.elephantsql.com/pausapcx',
// doesn't work:
connection: {
host: 'batyr.db.elephantsql.com',
user: 'pausapcx',
password: '***',
database: 'pausapcx',
},

API Call works for IPv4 Address (127.0.0.1) but get a "Error: connect ECONNREFUSED ::1:3001" when using localhost

So I have a very simple API call using fetch on my frontend to http://localhost:3001/test that gives me an error: Error: connect ECONNREFUSED ::1:3001
However, when I call that API directly (enter the api uri directly into my browser), it works just fine. Also when I change localhost to http://127.0.0.1:3001/test on my frontend fetch call, that works too.
This seems like it's gotta be a network error since ::1 and 127.0.0.1 resolve to the same address but one is IPv4 and the other is IPv6 right? Anyone have any thoughts on why this could be?
frontend fetch (BACKEND_URL = http://localhost:3001):
export async function getStaticProps() {
const res = await fetch(`${BACKEND_URL}/explore`, {
method: 'GET',
headers: {
"Content-Type": 'application/json',
Origin: BASE_URL,
},
});
...
}
Backend Server listening on port 3001 (PORT = 3001):
const PORT = process.env.PORT;
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server is running on port ${PORT}`);
});
Stack: NextJS frontend, ExpressJS backend, MongoDB Atlas DB, NextAuth for auth
A couple of things can be the issue:
You need to enclose the IPv6 address between brackets, like http://[::1]:3001/test
The service is only listening on the IPv4 address and not on the IPv6 address. Depending on the server you may need to configure the listening address differently
Your post doesn’t contain enough information to go into more detail. Please edit your post to include the actual code, service and configuration so we can help you further.
When you use "localhost" in the backend URL, that is by default going to be resolved to the IPv6 address ::1. However, looking at the backend server code, that backend is listening on 0.0.0.0 which is IPv4.
You need to make that backend listen on IPv6:
const PORT = process.env.PORT;
app.listen(PORT, '::', () => {
console.log(`Server is running on port ${PORT}`);
});

How to use `ioredis` to connect to Redis instance (AWS elasticcache) across ssh tunnel with SSL?

This seems to be something about ioredis and its support for TLS. This is all on a mac, Catalina, etc.
I have an elasticcache Redis instance running, inside a VPC. I tunnel to it with ssh,
ssh -L 6379:clustercfg.my-test-redis.amazonaws.com:6379 -N MyEC2
The following doesn't work with node 12.9, ioredis 4.19.4
> const Redis = require("ioredis");
> const redis = new Redis('rediss://127.0.0.1:6379');
[ioredis] Unhandled error event: Error [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames: IP: 127.0.0.1 is not in the cert's list:
at Object.checkServerIdentity (tls.js:287:12)
<repeated ... many times>
This doesn't work either:
> const Redis = require("ioredis");
> const redis = new Redis('redis://127.0.0.1:6379');
> redis.status
'connect'
> redis.set('fooo','barr').then(console.log).catch(console.error)
Promise { <pending> }
> redis.status
'connect'
Is there a way to let me do this with ioredis? This is just for debugging. If the first form is correct, is there a setting to allow "non-strict" validation of the cert or something?
This works (on a mac)
% openssl s_client -connect localhost:6379
set "fred" "Mary"
+OK
get "fred"
$4
Mary
This works (with redis installed via pip3)
#!/usr/bin/env python3
import redis
r = redis.Redis(host='127.0.0.1', ssl=True, port=6379)
r.set('foo', 'bar')
print(r.get('foo'))
While I wouldn't recommend this for production, you said this was for debugging.
You need to disable the server identity check. You can do that by overriding the function in the configuration with a noop:
const Redis = require("ioredis");
const redis = new Redis('rediss://127.0.0.1:6379', {
tls: {
checkServerIdentity: () => undefined,
}
});

peerjs working on loaclhost but not on heroku?

I'm running my node server on 3000 port and peer server on port 3001.In this scenario its working properly.But when deployed over heroku i'm running my server at 3000 and peer server over 443. In this scenario peerjs not wroking. It might be port alloction issue i guess but i'm unable to find the issue.
peer.js
const myPeer = new Peer( {
secure:true,
host: 'my-app-name.herokuapp.com',
port: 443
})
server.js
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
github link to project : link
New to Heroku. Any help will be appreciated!
Add this to your server file:
var ExpressPeerServer = require("peer").ExpressPeerServer;
var options = {
debug: true,
allow_discovery: true,
};
let peerServer = ExpressPeerServer(server, options);
app.use("/peerjs", peerServer);
And call on client side like this:
var peer = new Peer({
host: "yoursite.herokuapp.com",
port: "",
path: "/peerjs",
});
You Have to Host Two Apps on Heroku. First Your Main App and Second Your PeerJS Server. Because You Cannot Host your App On different Port (i.e. https://your-app-name.herokuapp.com:5000). And Then You can Connect Your Main App PeerJS Client With Your PeerJS Server by using this.
const myPeer = new Peer( {
secure:true,
host: 'my-peerjs-server-name.herokuapp.com',
port: 443
})
Happy Coding!
Just use this Heroku Element to deploy your own peer server with zero configuration. Connect to it from your client providing the host attribute as the url of your Heroku app without the https:// part and you may need to also set secure to true.
{
host: "you_app_name.herokuapp.com", // exclude protocol
secure: true
}
add this in server(index,app) file
const { ExpressPeerServer } = require("peer")
const peerServer = ExpressPeerServer(server, {
debug: true
})
app.use("/peerjs", peerServer);
and in client side add this
const myPeer = new Peer(undefined, {
path: "/peerjs",
host: "/",
port: "443",
})
port should same as your server.listen(port)
This will give invalid frame header for socket io but its fine

express socket.io Port 3000 is already in use

I would like to make real-time chat app on React-Native,
I have backend express
enter image description here
Now , I want to use socket.io in express backend , But not in app.js I would like to use socket.io in socketmessage.js , because I have more api this file
But return to me this error ; Port 3000 is already in use
How can i fix this problem?
I use this code for socket.io in socketmessage.js
var express = require('express');
var http = require('http');
var router = express.Router();
var socketio = require('socket.io');
var app = express();
var server = http.Server(app);
var websocket = socketio(server);
server.listen(3000, () => console.log('listening on *:3000'));
// The event will be called when a client is connected.
websocket.on('connection', (socket) => {
console.log('A client just joined on', socket.id);
});
module.exports = router;
Port 3000 on your machine might be already in use by other process. Follow below commands to free up the port.
lsof -i :3000
Above command lists down the process, using PID from the result execute following command:
kill -9 PID
Now restart your application.
On windows
netstat -a -n -o | find "3000"
Taskkill /PID <PIDNumber> /F
For windows:
Step 1: In command-line, type the following command:
netstat -ano | findstr yourPortNumber
This will give PID which is the process identifier
Step 2: Kill the task by typing the following command:
taskkill/PID yourPIDNumber
Step 3: If the second step does not work, append /F to the second command as follows:
taskkill/PID yourPIDNumber /F