Querying a mongo DB causes Heroku timeout? - javascript

I'm using a simple node app with an express server and attempting to deploy it to heroku and a single query to the database causes my app to crash with an H13 error after about 10 seconds. The error says it closed without response.
crash logs:
2022-06-20T04:01:55.992187+00:00 app[web.1]: const err = new MongooseError(message);
2022-06-20T04:01:55.992188+00:00 app[web.1]: ^
2022-06-20T04:01:55.992189+00:00 app[web.1]:
2022-06-20T04:01:55.992190+00:00 app[web.1]: MongooseError: Operation `classifications.findOne()` bufdOne()` buffering timed out after 10000ms
2022-06-20T04:01:55.992191+00:00 app[web.1]: at Timeout.<anonymous> (/app/node_modules/mongoose/lib/dgoose/lib/drivers/node-mongodb-native/collection.js:151:23)
2022-06-20T04:01:55.992191+00:00 app[web.1]: at listOnTimeout (node:internal/timers:559:17)) 2022-06-20T
2022-06-20T04:01:55.992192+00:00 app[web.1]: at processTimers (node:internal/timers:502:7)2022-06-20T04:01:55.992196+00:00 app[web.1]:
2022-06-20T04:01:55.992197+00:00 app[web.1]: Node.js v17.7.2 without re
2022-06-20T04:01:56.002582+00:00 heroku[router]: at=error code=H13 desc="Connection closed728b0fb8-d2 without response" method=GET path="/al/classes/class-1a" host=wcsn-backend.herokuapp.com s=503 bytes
request_id=728b0fb8-d2bf-44f4-ae5c-793401a76653 fwd="216.198.98.78" dyno=web.1 connect=0ms service=10015ms status=503 bytes=0 protocol=https
2022-06-20T04:01:56.161890+00:00 heroku[web.1]: Process exited with status 1
2022-06-20T04:01:56.253251+00:00 heroku[web.1]: State changed from up to crashed
The entire code can be found here.
or here with omitted commented out code:
server.get('/:state/:classification/:className', async (req, res) => {
let className = req.params.className.replaceAll('-', ' ');
className = className.replaceAll('/', ' ');
const { url } = await classificationsModel.findOne(
{
name: className.toLowerCase(),
associatedState: req.params.state.toUpperCase(),
},
{ url: 1, _id: 0 }
);
console.log(url);
res.json('hello world');
teamList = [];
});
Again locally this is produced in the console and 'hello world' is returned as json. Why is it different on heroku and how can I fix it?

Related

8Cant deploy Nodejs server in Heroku : 'Error: Cannot find module 'getStream''

My project seems to have no issues when running locally, but when I try to deploy it in heroku and open the app it gives me an application error. I tried checking the logs in heroku and this is what I get.
2022-09-14T20:31:10.475090+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19)
2022-09-14T20:31:10.475091+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-09-14T20:31:10.475091+00:00 app[web.1]: at Object.<anonymous> (/app/controllers/auth.js:1:19)
2022-09-14T20:31:10.475092+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1126:14)
2022-09-14T20:31:10.475092+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
2022-09-14T20:31:10.475092+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:1004:32)
2022-09-14T20:31:10.475093+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:839:12)
2022-09-14T20:31:10.475093+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19) {
2022-09-14T20:31:10.475093+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2022-09-14T20:31:10.475094+00:00 app[web.1]: requireStack: [
2022-09-14T20:31:10.475094+00:00 app[web.1]: '/app/controllers/auth.js',
2022-09-14T20:31:10.475094+00:00 app[web.1]: '/app/routes/auth.js',
2022-09-14T20:31:10.475095+00:00 app[web.1]: '/app/index.js'
2022-09-14T20:31:10.475095+00:00 app[web.1]: ]
2022-09-14T20:31:10.475095+00:00 app[web.1]: }
2022-09-14T20:31:10.660749+00:00 heroku[web.1]: Process exited with status 1
2022-09-14T20:31:10.723193+00:00 heroku[web.1]: State changed from starting to crashed
2022-09-14T20:31:10.726441+00:00 heroku[web.1]: State changed from crashed to starting
2022-09-14T20:31:13.020405+00:00 heroku[web.1]: Starting process with command `npm start`
2022-09-14T20:31:16.234548+00:00 app[web.1]:
2022-09-14T20:31:16.234562+00:00 app[web.1]: > server#1.0.0 start
2022-09-14T20:31:16.234562+00:00 app[web.1]: > node index.js
2022-09-14T20:31:16.234563+00:00 app[web.1]:
2022-09-14T20:31:16.387441+00:00 app[web.1]: node:internal/modules/cjs/loader:959
2022-09-14T20:31:16.387443+00:00 app[web.1]: throw err;
2022-09-14T20:31:16.387444+00:00 app[web.1]: ^
2022-09-14T20:31:16.387444+00:00 app[web.1]:
2022-09-14T20:31:16.387444+00:00 app[web.1]: Error: Cannot find module 'getStream'
2022-09-14T20:31:16.387445+00:00 app[web.1]: Require stack:
2022-09-14T20:31:16.387445+00:00 app[web.1]: - /app/controllers/auth.js
2022-09-14T20:31:16.387446+00:00 app[web.1]: - /app/routes/auth.js
2022-09-14T20:31:16.387446+00:00 app[web.1]: - /app/index.js
2022-09-14T20:31:16.387446+00:00 app[web.1]: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
2022-09-14T20:31:16.387447+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:804:27)
2022-09-14T20:31:16.387447+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19)
2022-09-14T20:31:16.387448+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-09-14T20:31:16.387448+00:00 app[web.1]: at Object.<anonymous> (/app/controllers/auth.js:1:19)
2022-09-14T20:31:16.387448+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1126:14)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Module.load (node:internal/modules/cjs/loader:1004:32)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:839:12)
2022-09-14T20:31:16.387449+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1028:19) {
2022-09-14T20:31:16.387450+00:00 app[web.1]: code: 'MODULE_NOT_FOUND',
2022-09-14T20:31:16.387450+00:00 app[web.1]: requireStack: [
2022-09-14T20:31:16.387450+00:00 app[web.1]: '/app/controllers/auth.js',
2022-09-14T20:31:16.387450+00:00 app[web.1]: '/app/routes/auth.js',
2022-09-14T20:31:16.387451+00:00 app[web.1]: '/app/index.js'
2022-09-14T20:31:16.387451+00:00 app[web.1]: ]
2022-09-14T20:31:16.387451+00:00 app[web.1]: }
2022-09-14T20:31:16.528452+00:00 heroku[web.1]: Process exited with status 1
2022-09-14T20:31:16.728856+00:00 heroku[web.1]: State changed from starting to crashed
2022-09-14T20:31:55.119571+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET pad="190.237.25.187" dyno= connect= service= status=503 bytes= protocol=https2022-09-14T20:42:01.202592+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=file-iu-sys.herokuapp.com request_id=b157556e-1a74-4d16-aef5-7e2e8cea2612 fwd="190.237.25.187" dyno= connect= service= status=503 bytes= protocol=https 2022-09-14T20:42:02.113418+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=file-iu-sys.herokuapp.com request_id=2c0cf996-5b33-4d15-b7c6-88cedd9f9c25 fwd="190.237.25.187" dyno= connect= service= status=503 bytes= protocol=https
I have tried checking for missing scripts, changing the Port to process.env.PORT, heroku repo:reset, deleting the git file and starting a new git init and even deleting the node_modules folder and running npm install. A similar app I tried hosting in heroku seems to run with no problems, the difference being this one has a mysql dependency and the heroku app has a clearDB plugin. The 'getstream' version is '8.0.1' (the one that runs without problems is '8.0.0' could that be the issue?).
this is my package.json file:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"crypto": "^1.0.1",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"getstream": "^8.0.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.16",
"stream-chat": "^6.5.1"
}
}
index.js file:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const authRoutes = require('./routes/auth.js')
const connection = mysql.createPool({
host: '*host-name*',
user: '*user*',
password: '*password*',
database: '*database*'
})
const app = express();
const PORT = process.env.PORT || 3001;
require('dotenv').config();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded());
//Routes
app.use('/auth', authRoutes);
app.get('/', (req, res) =>{
res.send('Server an')
})
//DB connection
//get from DB
app.get('/api/get', (req, res)=>{
const sqlSelect = 'SELECT * FROM anmeldungen';
connection.query(sqlSelect, (err, result)=>{
res.send(result);
if(err){
console.log('Error fetching from db');
}
});
})
//write to DB
app.use(bodyParser.urlencoded({extended: true}));
app.post('/api/insert', (req, res)=>{
const Student = req.body.Student;
const Fach = req.body.Fach;
//const Datum = req.body.Datum;
const Datum = new Date().toISOString().split('T')[0];
const DateiName = req.body.DateiName;
const Seite = req.body.Seite;
const Beschreibung = req.body.Beschreibung;
const sqlInsert = 'INSERT INTO anmeldungen(Student, Fach, Datum, DateiName, Seite, Beschreibung) VALUES(?,?,?,?,?,?)'
connection.query(sqlInsert, [Student, Fach, Datum, DateiName, Seite, Beschreibung], (err, result)=>{
console.log(result);
});
});
//delete from db
app.delete('/api/delete/:id', (req, res) =>{
const rowId = req.params.id;
const sqlDelete = "DELETE FROM anmeldungen WHERE id = ?";
connection.query(sqlDelete, rowId, (err, result)=>{
if(err) console.log(err);
})
})
//update rows in db
app.put('/api/update/:id', (req, res) =>{
const rowId = req.params.id;
const rowStat = req.body.Status;
const sqlUpdate = "UPDATE anmeldungen SET Status = ? WHERE id = ?";
connection.query(sqlUpdate, [rowStat, rowId], (err, result)=>{
if(err) console.log(err);
})
})
app.listen(PORT, () => console.log(`Server lauft auf port ${PORT}`));
auth.js:
const {connect} = require('getStream');
const bcrypt = require('bcrypt');
const StreamChat = require('stream-chat').StreamChat;
const crypto = require('crypto');
require('dotenv').config();
const api_key = process.env.STREAM_API_KEY;
const api_secret = process.env.STREAM_API_SECRET;
const app_id = process.env.STREAM_APP_ID;
const signup = async (req, res) => {
try {
//get from the front-end
const {fullName, username, password, phoneNumber} = req.body;
//create a random user Id: 16 digits in hexadecimal
const userId = crypto.randomBytes(16).toString('hex');
//connection to stream
const serverClient = connect(api_key, api_secret, app_id);
//create a password for the user token
const hashedPassword = await bcrypt.hash(password, 10);
//create token for the user
const token = serverClient.createUserToken(userId);
//get the values straight from the front-end to ensure secure authentication
res.status(200).json({token, fullName, username, userId, hashedPassword, phoneNumber})
} catch (error) {
console.log(error);
res.status(500).json({message: error});
}
};
const login = async(req, res) => {
try {
const {username, password} = req.body;
const serverClient = connect(api_key, api_secret, app_id);
//new instance of streamChat
const client = StreamChat.getInstance(api_key, api_secret);
//query all users that match this username
const {users} = await client.queryUsers({name: username});
if(!users.length) return res.status(400).json({message: 'Benutzername nicht gefunden.'});
//decrypt the password to see if it matches
const success = await bcrypt.compare(password, users[0].hashedPassword);
//create new token for this specific user's id.
const token = serverClient.createUserToken(users[0].id);
if(success){
res.status(200).json({token, fullName: users[0].fullName, username, userId: users[0].id});
} else {
res.status(500).json({message: 'falsches Kennwort'});
}
} catch (error) {
console.log(error);
res.status(500).json({message: error});
}
};
module.exports = {signup, login}
Found the problem in the auth.js file: I had written const {connect} = require('getStream'); instead of const {connect} = require('getstream');. So I guess it was due to naming conventions in a way. #Chris ty, that first question was right on the money.

ECONNREFUSED when trying to deploy to heroku

I'd really appreciate any help/insight.
I'm trying to push an application to Heroku, but for some reason, no matter what I try, I keep getting the error below:
2022-05-23T14:27:01.516414+00:00 app[web.1]: port: 3306,
2022-05-23T14:27:01.516414+00:00 app[web.1]: fatal: true
2022-05-23T14:27:01.516415+00:00 app[web.1]: }
2022-05-23T14:27:01.516415+00:00 app[web.1]: }
2022-05-23T14:27:01.661606+00:00 heroku[web.1]: Process exited with status 1
2022-05-23T14:27:01.740162+00:00 heroku[web.1]: State changed from starting to crashed
2022-05-23T14:27:02.914707+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=nameless-ravine-28520.herokuapp.com request_id=98b37974-ba16-45f7-acf3-e7e86339662f fwd="24.16.97.212" dyno= connect= service= status=503 bytes= protocol=https
2022-05-23T14:27:03.266073+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=nameless-ravine-28520.herokuapp.com request_id=8cd1f4ab-cebf-4e1f-921f-7882755f3ba7 fwd="24.16.97.212" dyno= connect= service= status=503 bytes= protocol=https
2022-05-23T14:27:49.000000+00:00 app[api]: Build started by user myemail#gmail.com
2022-05-23T14:28:03.242164+00:00 app[api]: Deploy 94abcb92 by user myemail#gmail.com
2022-05-23T14:28:03.242164+00:00 app[api]: Release v18 created by user myemail#gmail.com
2022-05-23T14:28:03.655978+00:00 heroku[web.1]: State changed from crashed to starting
2022-05-23T14:28:04.000000+00:00 app[api]: Build succeeded
2022-05-23T14:28:05.900985+00:00 heroku[web.1]: Starting process with command `npm start`
2022-05-23T14:28:07.670709+00:00 app[web.1]:
2022-05-23T14:28:07.670783+00:00 app[web.1]: > tech-blog#1.0.0 start
2022-05-23T14:28:07.670793+00:00 app[web.1]: > node server.js
2022-05-23T14:28:07.670793+00:00 app[web.1]:
2022-05-23T14:28:08.224358+00:00 app[web.1]: /app/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:92
2022-05-23T14:28:08.224360+00:00 app[web.1]: throw new SequelizeErrors.ConnectionRefusedError(err);
2022-05-23T14:28:08.224361+00:00 app[web.1]: ^
2022-05-23T14:28:08.224361+00:00 app[web.1]:
2022-05-23T14:28:08.224362+00:00 app[web.1]: ConnectionRefusedError [SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:4000
2022-05-23T14:28:08.224362+00:00 app[web.1]: at ConnectionManager.connect (/app/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:92:17)
2022-05-23T14:28:08.224363+00:00 app[web.1]: at processTicksAndRejections (node:internal/process/task_queues:96:5)
2022-05-23T14:28:08.224365+00:00 app[web.1]: at async ConnectionManager._connect (/app/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:216:24)
2022-05-23T14:28:08.224365+00:00 app[web.1]: at async /app/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:174:32
2022-05-23T14:28:08.224365+00:00 app[web.1]: at async ConnectionManager.getConnection (/app/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:197:7)
2022-05-23T14:28:08.224365+00:00 app[web.1]: at async /app/node_modules/sequelize/lib/sequelize.js:300:26
2022-05-23T14:28:08.224366+00:00 app[web.1]: at async MySQLQueryInterface.createTable (/app/node_modules/sequelize/lib/dialects/abstract/query-interface.js:94:12)
2022-05-23T14:28:08.224366+00:00 app[web.1]: at async Function.sync (/app/node_modules/sequelize/lib/model.js:937:5)
2022-05-23T14:28:08.224366+00:00 app[web.1]: at async Sequelize.sync (/app/node_modules/sequelize/lib/sequelize.js:374:9) {
2022-05-23T14:28:08.224367+00:00 app[web.1]: parent: Error: connect ECONNREFUSED 127.0.0.1:4000
2022-05-23T14:28:08.224367+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
2022-05-23T14:28:08.224367+00:00 app[web.1]: errno: -111,
2022-05-23T14:28:08.224368+00:00 app[web.1]: code: 'ECONNREFUSED',
2022-05-23T14:28:08.224368+00:00 app[web.1]: syscall: 'connect',
2022-05-23T14:28:08.224368+00:00 app[web.1]: address: '127.0.0.1',
2022-05-23T14:28:08.224368+00:00 app[web.1]: port: 4000,
2022-05-23T14:28:08.224369+00:00 app[web.1]: fatal: true
2022-05-23T14:28:08.224369+00:00 app[web.1]: },
2022-05-23T14:28:08.224369+00:00 app[web.1]: original: Error: connect ECONNREFUSED 127.0.0.1:4000
2022-05-23T14:28:08.224369+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
2022-05-23T14:28:08.224370+00:00 app[web.1]: errno: -111,
2022-05-23T14:28:08.224370+00:00 app[web.1]: code: 'ECONNREFUSED',
2022-05-23T14:28:08.224370+00:00 app[web.1]: syscall: 'connect',
2022-05-23T14:28:08.224370+00:00 app[web.1]: address: '127.0.0.1',
2022-05-23T14:28:08.224371+00:00 app[web.1]: port: 4000,
2022-05-23T14:28:08.224371+00:00 app[web.1]: fatal: true
2022-05-23T14:28:08.224371+00:00 app[web.1]: }
2022-05-23T14:28:08.224371+00:00 app[web.1]: }
2022-05-23T14:28:08.359638+00:00 heroku[web.1]: Process exited with status 1
2022-05-23T14:28:08.432804+00:00 heroku[web.1]: State changed from starting to crashed
2022-05-23T14:28:09.878995+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=nameless-ravine-28520.herokuapp.com request_id=bf095c36-5ad7-4489-b641-3f4081406547 fwd="24.16.97.212" dyno= connect= service= status=503 bytes= protocol=https
2022-05-23T14:28:10.284737+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=nameless-ravine-28520.herokuapp.com request_id=76849bc7-a25c-4705-83c2-e02436ca911d fwd="24.16.97.212" dyno= connect= service= status=503 bytes= protocol=https
2022-05-23T14:31:33.010867+00:00 heroku[web.1]: State changed from crashed to starting
2022-05-23T14:31:36.816915+00:00 heroku[web.1]: Starting process with command `npm start`
2022-05-23T14:31:38.599632+00:00 app[web.1]:
2022-05-23T14:31:38.599649+00:00 app[web.1]: > tech-blog#1.0.0 start
2022-05-23T14:31:38.599649+00:00 app[web.1]: > node server.js
2022-05-23T14:31:38.599650+00:00 app[web.1]:
2022-05-23T14:31:39.723960+00:00 app[web.1]: /app/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:92
2022-05-23T14:31:39.724079+00:00 app[web.1]: throw new SequelizeErrors.ConnectionRefusedError(err);
2022-05-23T14:31:39.724080+00:00 app[web.1]: ^
2022-05-23T14:31:39.724081+00:00 app[web.1]:
2022-05-23T14:31:39.724082+00:00 app[web.1]: ConnectionRefusedError [SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:3306
2022-05-23T14:31:39.724082+00:00 app[web.1]: at ConnectionManager.connect (/app/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:92:17)
2022-05-23T14:31:39.724083+00:00 app[web.1]: at processTicksAndRejections (node:internal/process/task_queues:96:5)
2022-05-23T14:31:39.724093+00:00 app[web.1]: at async ConnectionManager._connect (/app/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:216:24)
2022-05-23T14:31:39.724094+00:00 app[web.1]: at async /app/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:174:32
2022-05-23T14:31:39.724094+00:00 app[web.1]: at async ConnectionManager.getConnection (/app/node_modules/sequelize/lib/dialects/abstract/connection-manager.js:197:7)
2022-05-23T14:31:39.724094+00:00 app[web.1]: at async /app/node_modules/sequelize/lib/sequelize.js:301:26
2022-05-23T14:31:39.724095+00:00 app[web.1]: at async MySQLQueryInterface.tableExists (/app/node_modules/sequelize/lib/dialects/abstract/query-interface.js:102:17)
2022-05-23T14:31:39.724095+00:00 app[web.1]: at async Function.sync (/app/node_modules/sequelize/lib/model.js:939:21)
2022-05-23T14:31:39.724095+00:00 app[web.1]: at async Sequelize.sync (/app/node_modules/sequelize/lib/sequelize.js:373:9) {
2022-05-23T14:31:39.724096+00:00 app[web.1]: parent: Error: connect ECONNREFUSED 127.0.0.1:3306
2022-05-23T14:31:39.724096+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
2022-05-23T14:31:39.724096+00:00 app[web.1]: errno: -111,
2022-05-23T14:31:39.724097+00:00 app[web.1]: code: 'ECONNREFUSED',
2022-05-23T14:31:39.724097+00:00 app[web.1]: syscall: 'connect',
2022-05-23T14:31:39.724097+00:00 app[web.1]: address: '127.0.0.1',
2022-05-23T14:31:39.724098+00:00 app[web.1]: port: 3306,
2022-05-23T14:31:39.724098+00:00 app[web.1]: fatal: true
2022-05-23T14:31:39.724098+00:00 app[web.1]: },
2022-05-23T14:31:39.724098+00:00 app[web.1]: original: Error: connect ECONNREFUSED 127.0.0.1:3306
2022-05-23T14:31:39.724099+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
2022-05-23T14:31:39.724099+00:00 app[web.1]: errno: -111,
2022-05-23T14:31:39.724099+00:00 app[web.1]: code: 'ECONNREFUSED',
2022-05-23T14:31:39.724099+00:00 app[web.1]: syscall: 'connect',
2022-05-23T14:31:39.724100+00:00 app[web.1]: address: '127.0.0.1',
2022-05-23T14:31:39.724100+00:00 app[web.1]: port: 3306,
2022-05-23T14:31:39.724100+00:00 app[web.1]: fatal: true
2022-05-23T14:31:39.724100+00:00 app[web.1]: }
2022-05-23T14:31:39.724101+00:00 app[web.1]: }
2022-05-23T14:31:39.724107+00:00 app[web.1]:
2022-05-23T14:31:39.724107+00:00 app[web.1]: Node.js v17.7.2
2022-05-23T14:31:39.860343+00:00 heroku[web.1]: Process exited with status 1
2022-05-23T14:31:40.053008+00:00 heroku[web.1]: State changed from starting to crashed
2022-05-23T14:31:45.111051+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=nameless-ravine-28520.herokuapp.com request_id=5336970d-ba74-4b0a-a94d-bf59e04b5de3 fwd="24.16.97.212" dyno= connect= service= status=503 bytes= protocol=https
2022-05-23T14:31:45.471297+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=nameless-ravine-28520.herokuapp.com request_id=5dbf9333-0832-4a06-86be-71001fa9b245 fwd="24.16.97.212" dyno= connect= service= status=503 bytes= protocol=https
2022-05-23T14:31:07.000000+00:00 app[api]: Build started by user myemail#gmail.com
I spent almost the entire weekend looking at this and can't seem to figure it out. I've asked colleagues and none of their suggestions have worked, despite them having similar setups and being able to deploy to Heroku without issues.
Here's my /config/connection.js file:
const Sequelize = require('sequelize');
require('dotenv').config();
// create connection to our db
const sequelize = process.env.JAWSDB_URL
? new Sequelize(process.env.JAWSDB_URL)
: new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PW, {
host: '127.0.0.1.',
port: 3306,
dialect: 'mysql'
});
module.exports = sequelize;
And here's my server.js file:
const path = require('path');
const express = require('express');
const session = require('express-session');
const exphbs = require('express-handlebars');
const app = express();
const PORT = process.env.PORT || 4000;
const sequelize = require('./config/connection');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const helpers = require('./utils/helpers');
const hbs = exphbs.create({ helpers });
const sess = {
secret: 'Super secret secret',
cookie: {
maxAge: 900000
},
resave: false,
saveUninitialized: true,
store: new SequelizeStore({
db: sequelize
})
};
app.use(session(sess));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(require('./controllers/'));
sequelize.sync({ force: false }).then(() => {
app.listen(PORT, () => console.log('Now listening'));
});
Alternatively, here's the github repo: https://github.com/ilantimerman/tech-blog

I am trying to deploy Heroku and I am getting this error - code = H10, desc = app crashed method=GET path="/" status=503

I am trying to deploy Heroku and I am getting the following error. I have added the right script in the package.json as well and have web: node app.js in the Procfile as well. I am not sure what is going wrong. Any help will be appreciated.
2020-11-13T00:08:36.927175+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-11-13T00:08:36.937119+00:00 app[web.1]:
2020-11-13T00:08:36.937376+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-11-13T00:08:36.937493+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-11-13T00_08_36_928Z-debug.log
2020-11-13T00:08:37.022916+00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:08:37.099623+00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:08:37.103557+00:00 heroku[web.1]: State changed from crashed to starting
2020-11-13T00:08:40.893537+00:00 heroku[web.1]: Starting process with command `npm start`
2020-11-13T00:08:46.434145+00:00 app[web.1]:
2020-11-13T00:08:46.434159+00:00 app[web.1]: > NotesAppGIT#1.0.0 start /app
2020-11-13T00:08:46.434159+00:00 app[web.1]: > node app.js
2020-11-13T00:08:46.434160+00:00 app[web.1]:
2020-11-13T00:09:17.069358+00:00 app[web.1]: Unable to connect to database
2020-11-13T00:09:17.091792+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-11-13T00:09:17.092287+00:00 app[web.1]: npm ERR! errno 1
2020-11-13T00:09:17.111324+00:00 app[web.1]: npm ERR! NotesAppGIT#1.0.0 start: `node app.js`
2020-11-13T00:09:17.111442+00:00 app[web.1]: npm ERR! Exit status 1
2020-11-13T00:09:17.111634+00:00 app[web.1]: npm ERR!
2020-11-13T00:09:17.111801+00:00 app[web.1]: npm ERR! Failed at the NotesAppGIT#1.0.0 start script.
2020-11-13T00:09:17.111949+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-11-13T00:09:17.121499+00:00 app[web.1]:
2020-11-13T00:09:17.131690+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-11-13T00:09:17.131692+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-11-13T00_09_17_112Z-debug.log
2020-11-13T00:09:17.214878+00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:09:17.254440+00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:09:18.344634+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=notes-app-tanmay.herokuapp.com request_id=d05a7b5f-6e9b-46a5-9c32-65a8850ca8d8 fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:09:18.406623+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=notes-app-tanmay.herokuapp.com request_id=5313647a-7b67-498d-a6b3-609a8a99e33c fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:10:54.105165+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/getNotes" host=notes-app-tanmay.herokuapp.com request_id=5249c422-c8d0-4024-b15a-bb7d46cd0eb9 fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:20:05.000000+00:00 app[api]: Build started by user t.kulkarni#student.fontys.nl
2020-11-13T00:20:14.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/234008c5-0108-4501-8638-a536a6f392bc/activity/builds/68ca6bf4-5b07-4d64-b751-29189c2271cc
2020-11-13T00:21:56.000000+00:00 app[api]: Build started by user t.kulkarni#student.fontys.nl
2020-11-13T00:22:21.550005+00:00 app[api]: Deploy f854e773 by user t.kulkarni#student.fontys.nl
2020-11-13T00:22:21.550005+00:00 app[api]: Release v7 created by user t.kulkarni#student.fontys.nl
2020-11-13T00:22:22.544958+00:00 heroku[web.1]: State changed from crashed to starting
2020-11-13T00:22:26.000000+00:00 app[api]: Build succeeded
2020-11-13T00:22:26.340735+00:00 heroku[web.1]: Starting process with command `node app.js`
2020-11-13T00:22:58.765046+00:00 app[web.1]: Unable to connect to database
2020-11-13T00:22:58.831915+00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:22:58.903673+00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:22:58.907147+00:00 heroku[web.1]: State changed from crashed to starting
2020-11-13T00:23:02.186041+00:00 heroku[web.1]: Starting process with command `node app.js`
2020-11-13T00:23:34.617141+00:00 app[web.1]: Unable to connect to database
2020-11-13T00:23:34.674900+00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:23:34.746652+00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:23:35.188323+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=notes-app-tanmay.herokuapp.com request_id=616fd65b-5fd6-492e-b221-e1131b9cbff8 fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:23:38.591573+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/getNotes" host=notes-app-tanmay.herokuapp.com request_id=c708048e-b554-4f1f-856b-dc27f8f9318f fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
The following is my db.js file
// Import MongoDB Drivers
const MongoClient = require("mongodb").MongoClient; // Initialize mongodb to required MongoClient
const ObjectID = require('mongodb').ObjectID; // Initialize mongodb to required ObjectID
const dbname = "NotesAppGIT"; // State the DB name as "crud_mongodb"
const url = "mongodb://localhost:27017"; // Specify the location of mongoDB on local
const mongoOptions = {useNewUrlParser : true, useUnifiedTopology: true}; // Set flags for NewUrlParser & UnifiedTopology as true and pass them as MongoOptions
// Create connection between NodeJS & MongoDB Server
// State the initial default state as null
const state =
{
db : null
};
// Connect Method
const connect = (cb) => // pass call back
{
if(state.db) // If there is a database connection, call the callback function
{
cb();
}
else // If there is no database connection use the MongoClient to connect to the database
{
MongoClient.connect(url,mongoOptions,(err,client)=> // Use MongoClient to connect to the database
{
if(err) // If there are errors pass it through the call back function
{
cb(err);
}
else // If there are no errors set the state of the database and call the call back function
{
state.db = client.db(dbname);
cb();
}
});
}
}
// Primary Key Function
const getPrimaryKey = (_id) => // pass the id of the document
{
return ObjectID(_id); // Return the ObjectID along with it's ID. This will be used to query the database by ID
}
// Get DB Method
const getDB = ()=> // return the state of the database
{
return state.db;
}
module.exports = {getDB, connect, getPrimaryKey}; // Pass all the functions though module.exports
The following is my app.js file
// Import modules as variables
const express = require('express'); // Required for routing
const bodyParser = require("body-parser"); // Required to pass JSON data between Client Side & Server Side
const app = express(); // Create instance of express application
app.use(bodyParser.json()); // State the express application to use the body-parser module and parse JSON data through it
const path = require('path'); // Required to serve a static HTML file
const db = require("./db"); // Initialize db as required db path
const collection = "notes"; // Initialize name of the collections as "notes"
// GET Routes
// Send a static HTML file to the user
app.get('/', (req, res) => // Root get path & pass response & request object
{
res.sendFile(path.join(__dirname, 'index.html')); // Send a static HTML file from the path module
});
// Query the database for all the notes from the notes collection and return them to the user
app.get('/getNotes', (req, res) => // getNotes path & pass response & request object
{
db.getDB().collection(collection).find({}).toArray((err, documents) => // Call the getDB method (Line #51 od db.js file) & pass the name of the collection.Call the method find to have all the documents from the Notes collection.
{
if (err) // If there is an error, print an error in the console for the user
{
console.log(err);
} else // If there is no error, print the documents returned form the server and get the response of the documents in JSON format
{
res.json(documents);
}
});
});
// UPDATE Routes
// Pass a route parameter. The id is the primary key of the document needed to update. Pass the request & response function
app.put('/:id', (req, res) => {
const notesID = req.params.id; // get the ID of the notes
const userInput = req.body; // get the input of the notes from the user. User's data will be in the form of JSON
// Connect to the database and called the notes collection. Call a function findOneAndUpdate and pass the first argument as query object hence pass find by ID & notes. Pass the document for update, Pass the options and set returnOriginal to false. Pass the call back and pass error and result
db.getDB().collection(collection).findOneAndUpdate({_id: db.getPrimaryKey(notesID)}, {$set: {notes: userInput.notes}}, {returnOriginal: false}, (err, result) => {
if (err) // If there is an error, print an error in the console for the user
{
console.log(err);
} else // If there is no error then display the result as a response in JSON format
{
res.json(result);
}
});
});
// CREATE Route
app.post('/', (req, res) => {
const userInput = req.body;
db.getDB().collection(collection).insertOne(userInput, (err, result) => {
if (err)
console.log(err);
else {
res.json({result: result, document: result.ops[0]});
}
});
});
// DELETE Route
app.delete('/:id', (req, res) => {
const notesID = req.params.id;
db.getDB().collection(collection).findOneAndDelete({_id: db.getPrimaryKey(notesID)}, (err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
// Connect to the database [line #19 of db.js file]
db.connect((err) => // Pass a callback
{
if (err) // If there is an error in connecting to the database print "Unable to connect to database" in the console and terminate the application
{
console.log('Unable to connect to database');
process.exit(1);
} else // If a database connection is successful, listen on port 3000 and print "connected to database, app listening on port 3000" in the console
{
app.listen(process.env.PORT || 3000, () => {
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
}
})
The following is my package.json file
{
"name": "NotesAppGIT",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongodb": "^3.6.2",
"node": "^15.0.1",
"path": "^0.12.7"
}
}
I am not sure why this is happening. Any help will be very much appreciated. Thank you
Screenshot of the error -
It seems like there is an issue with the Database URL. Try replacing it with the Production Database URL.
db.js file
const url = "mongodb://localhost:27017"; // change this to production URL

Heroku Couldn't start my app.js (Code H10 status 503)

Let me start with screenshoots.
FULL ERROR LOG IS THERE
2020-06-15T10:46:45.640400+00:00 heroku[web.1]: Starting process with command `npm start`
2020-06-15T10:46:47.833544+00:00 app[web.1]:
2020-06-15T10:46:47.833563+00:00 app[web.1]: > learn-blog#1.0.0 start /app
2020-06-15T10:46:47.833563+00:00 app[web.1]: > node app.js
2020-06-15T10:46:47.833563+00:00 app[web.1]:
2020-06-15T10:47:22.069169+00:00 app[web.1]: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2020-06-15T10:47:22.069203+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:826:32)
2020-06-15T10:47:22.069204+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:335:15)
2020-06-15T10:47:22.069204+00:00 app[web.1]: at run (/app/app_server/server/server.js:26:20)
2020-06-15T10:47:22.069204+00:00 app[web.1]: at Object.<anonymous> (/app/app.js:3:1)
2020-06-15T10:47:22.069205+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-06-15T10:47:22.069205+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-06-15T10:47:22.069205+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-06-15T10:47:22.069205+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14)
2020-06-15T10:47:22.069206+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
2020-06-15T10:47:22.069206+00:00 app[web.1]: at internal/main/run_main_module.js:17:47 {
2020-06-15T10:47:22.069207+00:00 app[web.1]: reason: TopologyDescription {
2020-06-15T10:47:22.069207+00:00 app[web.1]: type: 'ReplicaSetNoPrimary',
2020-06-15T10:47:22.069207+00:00 app[web.1]: setName: null,
2020-06-15T10:47:22.069207+00:00 app[web.1]: maxSetVersion: null,
2020-06-15T10:47:22.069207+00:00 app[web.1]: maxElectionId: null,
2020-06-15T10:47:22.069208+00:00 app[web.1]: servers: Map {
2020-06-15T10:47:22.069208+00:00 app[web.1]: 'learningcluster-shard-00-01-izdfm.mongodb.net:27017' => [ServerDescription],
2020-06-15T10:47:22.069208+00:00 app[web.1]: 'learningcluster-shard-00-02-izdfm.mongodb.net:27017' => [ServerDescription],
2020-06-15T10:47:22.069208+00:00 app[web.1]: 'learningcluster-shard-00-00-izdfm.mongodb.net:27017' => [ServerDescription]
2020-06-15T10:47:22.069209+00:00 app[web.1]: },
2020-06-15T10:47:22.069209+00:00 app[web.1]: stale: false,
2020-06-15T10:47:22.069209+00:00 app[web.1]: compatible: true,
2020-06-15T10:47:22.069210+00:00 app[web.1]: compatibilityError: null,
2020-06-15T10:47:22.069210+00:00 app[web.1]: logicalSessionTimeoutMinutes: null,
2020-06-15T10:47:22.069210+00:00 app[web.1]: heartbeatFrequencyMS: 10000,
2020-06-15T10:47:22.069210+00:00 app[web.1]: localThresholdMS: 15,
2020-06-15T10:47:22.069210+00:00 app[web.1]: commonWireVersion: null
2020-06-15T10:47:22.069211+00:00 app[web.1]: }
2020-06-15T10:47:22.069211+00:00 app[web.1]: }
2020-06-15T10:47:22.143281+00:00 heroku[web.1]: Process exited with status 0
2020-06-15T10:47:22.184007+00:00 heroku[web.1]: State changed from starting to crashed
2020-06-15T10:48:10.737182+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=morning-taiga-29926.herokuapp.com request_id=840ea8ca-9d88-451d-9720-77cbafc687c0 fwd="88.238.178.195" dyno= connect= service= status=503 bytes= protocol=https
2020-06-15T10:48:11.205261+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=morning-taiga-29926.herokuapp.com request_id=2f1efa47-f83b-4d52-8d1c-2a7e45e7b666 fwd="88.238.178.195" dyno= connect= service= status=503 bytes= protocol=https
I checked my mongodb atlas cluster and my ip address is in whitelist. Also, i tried to set network access to 0.0.0.0/0 but its didn't worked too...
By the way, everything is works perfectly in my local address (8080).
I fixed it.
I added this things in my code;
mongoose.Promise = global.Promise;
...
const PORT = process.env.PORT || 8080;
const CONNECTION_URI = process.env.MONGODB_URI || 'mongodb+srv://learnBlogAdmin:learnBlogAdminsPowsyetmiş22a#learningcluster-izdfm.mongodb.net/personalblog?retryWrites=true&w=majority';
...
run()
.then(() => {
console.log("IT WORKS");
})
.catch((err) => {
console.log(err);
throw err;
})
And its worked.

Failed to bind to $PORT when trying to deploy Python/flask app to Heroku

I'm trying for the first time to remotely deploy my Python flask web app on Heroku and of course I'm encountering some problems.
My python code looks like this:
# server settings
HOST = '127.0.0.1'
PORT = int(os.environ.get('PORT', 5000))
DEBUG_MODE = True
...
#functions definition
...
app = Flask(__name__)
#app.route("/geodesicDistance")
def geodesicDistance():
t_start = time.time()
query = parse_query(request.args)
if query:
position = geocode_address(query)
if (position) and (len(position[u'results'])>0):
lat = position[u'results'][0][u'geometry'][u'location'][u'lat']
lng = position[u'results'][0][u'geometry'][u'location'][u'lng']
response = create_response(200,
'Good query',
lat,
lng,
position[u'results'][0][u'formatted_address'],
get_distance(lat,lng)
)
else:
response = create_response(400,
'Bad formed query',
'',
'',
'',
'')
else:
response = create_response(204,
'No query made',
givenAddress['lat'],
givenAddress['lng'],
'White Bear Yard, 144a Clerkenwell Road, London, EC1R 5DF, UK',
0.0
)
response['result']['elapsed'] = (time.time() - t_start)*1.0e3
http_response = make_response(json.dumps(response))
http_response.headers['Content-type'] = 'application/json'
http_response.headers['Access-Control-Allow-Origin'] = '*'
return http_response
if __name__=="__main__":
app.run(debug=DEBUG_MODE, host=HOST, port=PORT)
And my JavaScript:
<script type="text/javascript">
function checkGeolocation() {
if (navigator.geolocation) {
refresh();
} else {
$('#results')[0].innerHTML = "<p>Your browser doesn't support geolocation <br /></p>";
}
}
function getDistance(position) {
url = 'http://127.0.0.1:5000/geodesicDistance';
query =position.coords.latitude.toString()+','+position.coords.longitude.toString();
$.get(url, {'q': query},function(data) {
$('#results .distance')[0].innerHTML = Math.round(data['result']['distance']*1000)/1000;
})
}
function handleError(error) {
alert(error.message);
}
function refresh() {
navigator.geolocation.getCurrentPosition(getDistance,handleError);
}
$(document).ready(function(){
checkGeolocation();
});
</script>
This is the error Heruku gives according to the logs
2013-08-21T00:12:55.985496+00:00 heroku[web.1]: Starting process with command `python geodesicDistance.py`
2013-08-21T00:12:57.326395+00:00 app[web.1]: * Running on http://127.0.0.1:12176/
2013-08-21T00:12:57.326395+00:00 app[web.1]: * Restarting with reloader
2013-08-21T00:13:56.914333+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2013-08-21T00:13:56.914595+00:00 heroku[web.1]: Stopping process with SIGKILL
2013-08-21T00:13:58.185305+00:00 heroku[web.1]: Process exited with status 137
2013-08-21T00:13:58.205874+00:00 heroku[web.1]: State changed from starting to crashed
2013-08-21T00:18:23.999482+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=stormy-sands-9363.herokuapp.com fwd="93.46.195.73" dyno= connect= service= status=503 bytes=
I believe it's a port problem and the cause may be this line in my javascript code
url = 'http://127.0.0.1:5000/geodesicDistance';
not having the possibility to set a static port with Heroku
My Procfile (it's working in local)
Web: python geodesicDistance.py
Any advice?
if you look at this page https://devcenter.heroku.com/articles/dynos (search for "web dynos") you see that Heroku sets the environment variable $PORT
So, even if you can't specify the port Flask will run on, you can at least know it from the $PORT variable.

Categories

Resources