I have followed traversy media tutorial to deploy nodejs app on digital-ocean. I am using postgres database of digital ocean. However on running node app.js command I am getting error
I have tried to follow many answers on stackoverflow but they have not solved the problem
app.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const db = require('./queries') // contains all query functions
const port = 3000
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.use(cors())
app.get('/runs', db.getPlayers)
app.post('/year', db.getByYear)
//Handle production
app.use(express.static(__dirname+'/public/'))
//Handle SPA
app.get(/.*/, (request, response) => response.sendFile(__dirname+'/public/index.html') );
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
Error which I am getting is:-
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at Server.setupListenHandle [as _listen2] (net.js:1367:14)
at listenInCluster (net.js:1408:12)
at Server.listen (net.js:1492:7)
at Function.listen (/home/vineet/IPL-Stats-Analysis-Dashboard/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/vineet/IPL-Stats-Analysis-Dashboard/app.js:63:5)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
I am not familiar with said tutorial - but the error denotes that another process (probably the same express app) is already listening on port 3000.
On Linux you can list all running process with the command ps aux. Look for another node process. If there is none - you can find which processes are listening on which ports by running lsof -Pnl +M -i4 for ipv4 addresses and lsof -Pnl +M -i6 for ipv6.
Or simply do curl http://localhost:3000 in the Digitalocean droplet.
If were your OS is Linux, just type on your terminal which is killall -9 node
Related
I want to run a node server on port 3004 in my ec2 instance which has an IP of 13...*
when I use the IP address as the host I get the following error
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRNOTAVAIL 13.*.*.*:3004
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at Server.setupListenHandle [as _listen2] (net.js:1350:19)
at listenInCluster (net.js:1408:12)
at doListen (net.js:1517:7)
at _combinedTickCallback (internal/process/next_tick.js:141:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:695:11)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
I also tried using 0.0.0.0 as my host and allowing port 3004 using ufw
ufw allow 3004
the server does run but when I make the following request using chrome browser
13.*.*.*:3004
i get ERR_CONNECTION_TIMED_OUT error in browser
I have another node web server running on port 3000 which is working fine
what should i do.
this is my node server code
const http = require('http');
const hostname = '0.0.0.0';
const port = 3004;
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}/`);
});
So, I have a simple express server which connects to the mongoDB atlas by mongoose.
And for example I starting the server, everything works fine but when I do restart(no matter with nodemon or just by using node) I got an error:
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (net.js:1313:16)
at listenInCluster (net.js:1361:12)
at Server.listen (net.js:1447:7)
at Function.listen (C:\Users\Олег\e-commerce-mern\MERN-shop-app\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\Олег\e-commerce-mern\MERN-shop-app\backend\server.js:36:20)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1340:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 5000
}
and after restarting one or few times my server starts working just fine without the error, but then, after saving again the problem repeats and i don't know why.
db.js:
const mongoose = require('mongoose');
const mongoConnection = () => {
return mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
};
module.exports = mongoConnection;
server.js:
const express = require('express');
const products = require('./data/products'); //my mock data
const dotenv = require('dotenv');
// eslint-disable-next-line no-unused-vars
const colors = require('colors');
const dbConnect = require('./config/db');
dotenv.config();
dbConnect()
.then(() => {
// callback();
console.log('db connected');
})
.catch((err) => {
console.error(`Error: ${error.message}`.red.underline.bold);
process.exit(1);
});
const app = express();
app.get('/', (req, res) => {
res.send('app is running');
});
app.get('/api/products', (req, res) => {
res.json(products);
});
app.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id);
res.json(product);
});
const PORT = process.env.port || 5000;
const server = app.listen(PORT,
// eslint-disable-next-line max-len
console.log(`server running in ${process.env.NODE_ENV} on port ${PORT}`.yellow.bold));
process.on('unhandledRejection', (err) => {
console.log('err', err.name, err.message);
console.log('unhadled rejection');
server.close(() => {
process.exit(1);
});
});
As you see, nothing too fancy here, yes, I understand that my port isn't killed on restart but I don't understand that behaviour and how to prevent it.
P.S. I'm using windows.
This error raised because any application running on port 5000.
To fix it you just need to kill the running application on port 5000.
Follow the steps below:
Step 0: stop your application If you are currently trying to run it on port 5000
Step 1: run command prompt as administrator
Step 2: run
-->" netstat -ano | findstr :5000 " <--
command to find the running application's pid number.
Note: In my case it is 4208
Step 4: run taskkill /PID {pid number} /F to kill the running process.
Now you can run your app on port 5000
Update : Got a shortcut to kill the process
Just run TASKKILL /IM node.exe /F
Then start your application :-)
i am still new in backend but i am facing an error since yesterday whenever i try to run my server. BELOW IS MY CODE AND ERROR
const express = require("express");
const app = express();
PORT = 8443;
app.listen("PORT", () => {
console.log("Server up and running")
});
AND HERE IS MY ERROR
events.js:288
throw er; // Unhandled 'error' event
^
Error: listen EACCES: permission denied PORT
←[90m at Server.setupListenHandle [as _listen2] (net.js:1292:21)←[39m
←[90m at listenInCluster (net.js:1357:12)←[39m
←[90m at Server.listen (net.js:1456:5)←[39m
at Function.listen (C:\Users\AbTorres9\Desktop\YelpCamp\node_modules\←[4mexpress←[24m\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\AbTorres9\Desktop\YelpCamp\app.js:6:5)
←[90m at Module._compile (internal/modules/cjs/loader.js:1158:30)←[39m
←[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)←[39m
←[90m at Module.load (internal/modules/cjs/loader.js:1002:32)←[39m
←[90m at Function.Module._load (internal/modules/cjs/loader.js:901:14)←[39m
←[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)←[39m
Emitted 'error' event on Server instance at:
←[90m at emitErrorNT (net.js:1336:8)←[39m
←[90m at processTicksAndRejections (internal/process/task_queues.js:84:21)←[39m {
code: ←[32m'EACCES'←[39m,
errno: ←[32m'EACCES'←[39m,
syscall: ←[32m'listen'←[39m,
address: ←[32m'PORT'←[39m,
port: ←[33m-1←[39m
}
[nodemon] app crashed - waiting for file changes before starting...
const express = require("express");
const app = express();
const PORT = 8443;
app.listen(PORT, () => {
console.log("Server up and running")
});
you had some errors first of all you did not initialized the PORT and second you passed PORT as string in app.listen()
You are missing a view normal JavaScript things. Like defining port. And the .listen function takes in the port variable rather than a string saying "PORT"
See working example:
const express = require('express');
const app = express();
const port = 8443;
app.listen(port, () => console.log(`Server running on port ${port}!`));
#Abhishek, I think on which port are you using that is block by your environment kindly allow it on the firewall or just disable the firewall and access again it works for you!!
You should use the variable and not the string in the app.listen() function. Try to use something like this:
app.listen(PORT, () => {
console.log("Server up and running")
});
I am learning rest api but keep on getting the following error. Why? I am using Node JS, Mongo DB and Express. I am new to this.
Code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//connect to mongoose
mongoose.connect('mongodb://localost/bookstore');
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Please use /api for the API.');
});
app.listen(3000);
console.log('Running on port 3000...');
Error:
(node:7908) DeprecationWarning: current URL string parser is deprecated, and wil
l be removed in a future version. To use the new parser, pass option { useNewUrl
Parser: true } to MongoClient.connect.
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Server.setupListenHandle [as _listen2] (net.js:1360:14)
at listenInCluster (net.js:1401:12)
at Server.listen (net.js:1485:7)
at Function.listen (C:\apiproject\bookstore\node_modules\express\lib\applica
tion.js:618:24)
at Object.<anonymous> (C:\apiproject\bookstore\app.js:14:5)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
The error is showing that port 3000 is already in use.
Please get the list of all the ports in use and then kill the port 3000 and run the application again
netstat -a -o to get all the running ports
And then
Taskkill /PID -f (PID)
I have a Node app that I run on port 3000 locally. This error started popping up recently:
➜ web-frontend git:(feature/WEB-6880__CheckoutBackButton) yarn start
yarn run v1.2.1
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1259:14)
at listen (net.js:1295:10)
at Server.listen (net.js:1391:5)
at EventEmitter.listen (/Users/durham/Sites/web-frontend/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/Users/durham/Sites/web-frontend/server/index.js:79:5)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
➜ web-frontend git:(feature/WEB-6880__CheckoutBackButton)
I would kill any process using that port and it would restart:
➜ ~ sudo lsof -i tcp:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
httpd 1926 root 6u IPv6 0x99102dc7c7853bbb 0t0 TCP *:hbci (LISTEN)
httpd 1931 _www 6u IPv6 0x99102dc7c7853bbb 0t0 TCP *:hbci (LISTEN)
➜ ~ sudo kill -9 1926
➜ ~ sudo kill -9 1931
kill: 1931: No such process
➜ ~ z front
➜ web-frontend git:(feature/WEB-6880__CheckoutBackButton) yarn start
yarn run v1.2.1
$ export $(cat internals/env/dev); NODE_ENV=development node server
events.js:160
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at Server._listen2 (net.js:1259:14)
at listen (net.js:1295:10)
at Server.listen (net.js:1391:5)
at EventEmitter.listen (/Users/hco/Sites/web-frontend/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/Users/hco/Sites/web-frontend/server/index.js:79:5)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
error Command failed with exit code 1.
I restart my machine and try to start my app to the same error.
What might be the issue here? This is new and I can’t think of anything I’ve changed that might have caused it.
Express app code, as requested:
const express = require('express');
const logger = require('./logger');
const { sources } = require('../internals/config');
const argv = require('minimist')(process.argv.slice(2));
const setup = require('./middlewares/frontendMiddleware');
const path = require('path');
const resolve = require('path').resolve;
const fs = require('fs');
const morgan = require('morgan');
const app = express();
const DEFAULT_PORT = 3000;
/**
* Set up Morgan for logging errors to the server.
* All errors are logged to the `access.log` file in the directory the
* site is run from.
*/
const errorLog = process.env.NODE_ENV === 'production'
? '/var/log/web2/web2.log'
: path.join(process.cwd(), '../access.log');
// create a write stream (in append mode)
const accessLogStream = fs.createWriteStream(errorLog, { flags: 'a' });
// setup the logger
app.use(morgan('combined', {
skip: (req, res) => res.statusCode < 400, // eslint-disable-line no-magic-numbers
stream: accessLogStream
}));
// remove trailing slashes
app.use((req, res, next) => {
if (req.path.length > 1 && /\/$/.test(req.path)) {
const query = req.url.slice(req.path.length);
res.redirect(301, req.path.slice(0, -1) + query);
} else {
next();
}
});
// Proxy package so we can manage API requests with Node instead of the client.
const proxy = require('express-http-proxy');
/**
* Incorporate API middleware with proxy
* The proxy helps work around the CORS issue with standard Ajax requests
* on the client. There are further methods that can be taken advantage of with
* the express-http-proxy library. Take a look here:
* https://github.com/villadora/express-http-proxy
*
*
* Proxies requests for the H&Co API.
* Example URL to test: /api/v1/product_lines?sort=name
* API documentation: https://swagger.typography.com/api2/
*/
app.use('/api', proxy(sources.apiUrl, {
proxyReqOptDecorator: (proxyReq) => {
if (proxyReq.headers['authorization-api']) {
proxyReq.headers['Authorization'] = proxyReq.headers['authorization-api']; // eslint-disable-line
}
return proxyReq;
}
}));
// In production we need to pass these values in instead of relying on webpack
setup(app, {
outputPath: resolve(process.cwd(), 'build'),
publicPath: '/'
});
// get the intended port number, use port 3000 if not provided
const port = argv.port || process.env.PORT || DEFAULT_PORT;
// Start your app.
/* eslint consistent-return: 0 */
app.listen(port, (err) => {
if (err) {
return logger.error(err.message);
}
logger.appStarted(port, null, sources.apiUrl);
});
instead of using "app.listen", start your server like so:
const server = require("http").createServer(app);
server.listen(port, () => console.log("server started"));
then you'll be able to close the server and free the port when your app exits
function exit(message) {
if (message) console.log(message);
server.close();
process.exit();
}
process.on("exit", exit);
process.on("SIGINT", exit);
process.on("uncaughtException", exit);