express socket.io Port 3000 is already in use - express

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

Related

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

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.

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,
}
});

Botkit With Express

The documentation at Botkit (https://github.com/howdyai/botkit/blob/master/readme-facebook.md) is pretty not meaningful at all:
// if you are already using Express, you can use your own server instance...
// see "Use BotKit with an Express web server"
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
Moreover, without a custom webserver (like express), Botkit doesnt provide a way to set the custom local url (instead, it simply chooses 0.0.0.0, which is impractical).
Is anyone successfully assembling app = require('express')(); into the setupWebserver in Botkit (specially for Messenger). If yes, please present the full code.
Hostname for the built in express server can be set when creating your controller:
var controller = Botkit.facebookbot({
hostname: 'YOUR_HOST_NAME',
verify_token: '',
access_token: ''
})
controller.setupWebserver and controller.createWebhookEndpoints are helper functions within botkit to do just what they describe, create an express webserver and webhook endpoints, respectively.
To implement your own webserver, you just need to setup a webhook endpoint for the botkit controller to receive message POST data at and perform auth handshakes.
By botkit convention this is /{platform}/receive so for facebook /facebook/receive but you can use whatever you like.
To use a custom express server with Botkit, first create a basic webserver.
// components/express_webserver.js
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var debug = require('debug')('botkit:webserver');
module.exports = function(controller, bot) {
var webserver = express();
webserver.use(bodyParser.json());
webserver.use(bodyParser.urlencoded({ extended: true }));
webserver.use(express.static('public'));
// You can pass in whatever hostname you want as the second argument
// of the express listen function, it defaults to 0.0.0.0 aka localhost
webserver.listen(process.env.PORT || 3000, null, function() {
console.log('Express webserver configured and listening at ',
process.env.HOSTNAME || 'http://localhost/' + ':' + process.env.PORT || 3000);
});
// Register our routes, in this case we're just using one route
// for all incoming requests from FB
// We are passing in the webserver we created, and the botkit
// controller into our routes file so we can extend both of them
require('./routes/incoming-webhook')(webserver, controller)
controller.webserver = webserver;
return webserver;
}
Next you need to create the routes for webhook endpoints, we're doing this in a separate file as is common with express
// components/routes/webhook.js
module.exports = function(webserver, controller) {
// Receive post data from fb, this will be the messages you receive
webserver.post('/facebook/receive', function(req, res) {
// respond to FB that the webhook has been received.
res.status(200);
res.send('ok');
var bot = controller.spawn({});
// Now, pass the webhook into be processed
controller.handleWebhookPayload(req, res, bot);
});
// Perform the FB webhook verification handshake with your verify token
webserver.get('/facebook/receive', function(req, res) {
if (req.query['hub.mode'] == 'subscribe') {
if (req.query['hub.verify_token'] == controller.config.verify_token) {
res.send(req.query['hub.challenge']);
} else {
res.send('OK');
}
}
});
}
Once you have created these two files, you will use require and pass your controller into the express module. Your main bot file should look something like this
// bot.js
var Botkit = require('botkit');
// Create the Botkit controller, which controls all instances of the bot.
var controller = Botkit.facebookbot({
debug: true,
verify_token: process.env.verify_token,
access_token: process.env.page_token,
});
// Set up an Express-powered webserver to expose oauth and webhook endpoints
// We are passing the controller object into our express server module
// so we can extend it and process incoming message payloads
var webserver = require(__dirname + '/components/express_webserver.js')(controller);
You can find in github a, MIT-licensed, full Demo of running BotKit for Facebook Messenger on an Express server with MongoDB storage.
Here is the main server.js
// modules =================================================
var express = require('express') // framework d'appli
var app = express()
var bodyParser = require('body-parser') // BodyParser pour POST
var http = require('http').Server(app) // préparer le serveur web
var dotenv = require('dotenv')
var path = require('path')
// configuration ===========================================
// load environment variables,
// either from .env files (development),
// heroku environment in production, etc...
dotenv.load()
app.use(express.static(path.join(__dirname, '/public')))
// parsing
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing url encoded
// view engine ejs
app.set('view engine', 'ejs')
// routes
require('./app/routes/routes')(app)
// port for Heroku
app.set('port', (process.env.PORT || 5000))
// START ===================================================
http.listen(app.get('port'), function () {
console.log('listening on port ' + app.get('port'))
})
okay so here goes i was trying the same thing and have been able to start the botkit up with a custom url on express. You dont have to worry about this code at all:
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
This repository has its own code with will work with a mongodb database and a express server.
git clone https://github.com/mvaragnat/botkit-messenger-express-demo.git
sudo npm install express --save
sudo npm link body-parser
sudo npm link dotenv
sudo npm install --save botkit
sudo npm install --save monkii
sudo npm install --save mongodb
sudo npm install --save request
sudo npm install --save ejs
In all of the above steps you can perform:
sudo npm link botkit
etc
Finally run node server.js
lt --subdomain botkit --port 5000
restart node server.js
Dont Forget to add your variables to .env file in the directory.
All your traffic on local host will be redirected to the localtunnel, you can get a url using the lt --subdomain name --port 5000
Use this generated url in the webhooks on your page and your bot should be online.

Gulp task to SSH and then mysqldump

So I've got this scenario where I have separate Web server and MySQL server, and I can only connect to the MySQL server from the web server.
So basically everytime I have to go like:
step 1: 'ssh -i ~/somecert.pem ubuntu#1.2.3.4'
step 2: 'mysqldump -u root -p'password' -h 6.7.8.9 database_name > output.sql'
I'm new to gulp and my aim was to create a task that could automate all this, so running one gulp task would automatically deliver me the SQL file.
This would make the developer life a lot easier since it would just take a command to download the latest db dump.
This is where I got so far (gulpfile.js):
////////////////////////////////////////////////////////////////////
// Run: 'gulp download-db' to get latest SQL dump from production //
// File will be put under the 'dumps' folder //
////////////////////////////////////////////////////////////////////
// Load stuff
'use strict'
var gulp = require('gulp')
var GulpSSH = require('gulp-ssh')
var fs = require('fs');
// Function to get home path
function getUserHome() {
return process.env.HOME || process.env.USERPROFILE;
}
var homepath = getUserHome();
///////////////////////////////////////
// SETTINGS (change if needed) //
///////////////////////////////////////
var config = {
// SSH connection
host: '1.2.3.4',
port: 22,
username: 'ubuntu',
//password: '1337p4ssw0rd', // Uncomment if needed
privateKey: fs.readFileSync( homepath + '/certs/somecert.pem'), // Uncomment if needed
// MySQL connection
db_host: 'localhost',
db_name: 'clients_db',
db_username: 'root',
db_password: 'dbp4ssw0rd',
}
////////////////////////////////////////////////
// Core script, don't need to touch from here //
////////////////////////////////////////////////
// Set up SSH connector
var gulpSSH = new GulpSSH({
ignoreErrors: true,
sshConfig: config
})
// Run the mysqldump
gulp.task('download-db', function(){
return gulpSSH
// runs the mysql dump
.exec(['mysqldump -u '+config.db_username+' -p\''+config.db_password+'\' -h '+config.db_host+' '+config.db_name+''], {filePath: 'dump.sql'})
// pipes output into local folder
.pipe(gulp.dest('dumps'))
})
// Run search/replace "optional"
SSH into the web server runs fine, but I have an issue when trying to get the mysqldump, I'm getting this message:
events.js:85
throw er; // Unhandled 'error' event
^
Error: Warning:
If I try the same mysqldump command manually from the server SSH, I get:
Warning: mysqldump: unknown variable 'loose-local-infile=1'
Followed by the correct mylsql dump info.
So I think this warning message is messing up my script, I would like to ignore warnings in cases like this, but don't know how to do it or if it's possible.
Also I read that using the password directly in the command line is not really good practice.
Ideally, I would like to have all the config vars loaded from another file, but this is my first gulp task and not really familiar with how I would do that.
Can someone with experience in Gulp orient me towards a good way of getting this thing done? Or do you think I shouldn't be using Gulp for this at all?
Thanks!
As I suspected, that warning message was preventing the gulp task from finalizing, I got rid of it by commenting the: loose-local-infile=1 From /etc/mysql/my.cnf

Node express server, CORS API restriction, including an entry in my development machine’s hosts file

I am trying to use an API that has an API CORS policy that does not support browser requests from any domain. In order to allow clientside JavaScript code to access the API, whilst developing my application, I have been advised to I serve my webapp from '*.thisCompany.com' domain.
It was advised to include an entry in my development machine’s hosts file, as follows, which I have done:
$ echo '127.0.0.1 localhost.thisCompany.com' >> /etc/hosts
Following this command when I run sudo nano /private/etc/hosts
this is the screen that I see.
Host Database
localhost is used to configure the loopback interface
when the system is booting. Do not change this entry.
127.0.0.1 localhost
127.0.0.1 localhost.thisCompany.com
And then I have been told that I should be able access my webapp at http://localhost.thisCompany.com.
I am using node express as my server and the code in my server.js file looks like this
var express = require('express');
var server = express();
var path = require('path');
var port = process.env.PORT || 'thisCompany.com';
server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));
server.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/views/index.html'));
});
server.listen(port, function() {
console.log("Node app is running at localhost:" + port)
});
Can anyone advise what steps I should follow to enable me to call this API and bypass the API CORS policy?
I have read various other posts here, and also other articles online, however I cannot find the solution. Really hoping someone on this can help.
Thanks, Paul
I misunderstood how I was supposed to view a page locally on my computer after amending the hosts file on my local machine. I didn't need to add anything to my express server. The express server code remained as follows:
var express = require('express');
var server = express();
var path = require('path');
var port = process.env.PORT || 3000;
server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));
server.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/views/index.html'));
});
server.listen(port, function() {
console.log("Node app is running at localhost:" + port)
});
After adding the line mentioned in my original post to my hosts file on my local machine, I then needed to launch my server and access the page by following this link.
http://localhost.thisCompany.com:3000/
Although this is quite a niche issue, I hope this post helps someone in the future.