Issue connection to database - javascript

I have an application with a frontend that uses React and a backend that uses the Nodejs environment with the Express framework.
To communicate and store the data I use MongoDB.
I have been developing this application for a few weeks now and everything is working fine until today.
This morning again I developed and I could test everything, it responded well.
Since two hours when I write npm start in my terminal on vscode in the backend folder, I get an error while before my server was running fine. I want to specify that I made a 30min break between when I stopped coding this morning and when I started again this afternoon, I didn't change anything in the code in the meantime but the server doesn't start anymore. I also want to say that npm start in my frontend folder is still working fine.
Implementing mongo db in my backend code
db.js in models folder
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI, { useNewURLParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function () {
console.log('Connected')
});
implementation of mongo in app.js of backend folder
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var logger = require("morgan");
var cors = require("cors");
require('dotenv').config();
var whitelist = ['http://localhost:3000']
var corsOption = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
var getAPIRouter = require("./routes/apiRoutes.js");
var app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(cors(corsOption));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
app.use("/", getAPIRouter);
require('./routes/auth.routes')(app);
require('./routes/user.routes')(app);
const db = require("./models");
const Role = db.role;
db.mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
//just for first time running
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "moderator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: "admin"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
});
}
});
}
app.use(function (req, res, next) {
next(createError(404));
});
app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
My error in the terminal
PS C:\Users\deyga\Documents\GitHub\PPE\backendPPE> npm start
> backendppe#0.0.0 start C:\Users\deyga\Documents\GitHub\PPE\backendPPE
> node ./bin/www
Successfully connect to MongoDB.
connection error 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/
at NativeConnection.Connection.openUri (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:340:10
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:1174:10)
at Mongoose.connect (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:339:20)
at Object.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\models\db.js:2:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'cluster0-shard-00-00.0ynbf.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.0ynbf.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.0ynbf.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-sujybn-shard-0',
logicalSessionTimeoutMinutes: undefined
}
}
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
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/
at NativeConnection.Connection.openUri (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:340:10
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:1174:10)
at Mongoose.connect (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:339:20)
at Object.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\models\db.js:2:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'cluster0-shard-00-00.0ynbf.mongodb.net:27017' => ServerDescription {
_hostAddress: HostAddress {
isIPv6: false,
host: 'cluster0-shard-00-00.0ynbf.mongodb.net',
port: 27017
},
address: 'cluster0-shard-00-00.0ynbf.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2826297,
lastWriteDate: 0,
error: MongoNetworkError: connect ETIMEDOUT 108.129.27.210:27017
at connectionFailureError (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:381:20)
at TLSSocket.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at TLSSocket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
},
'cluster0-shard-00-01.0ynbf.mongodb.net:27017' => ServerDescription {
_hostAddress: HostAddress {
isIPv6: false,
host: 'cluster0-shard-00-01.0ynbf.mongodb.net',
port: 27017
},
address: 'cluster0-shard-00-01.0ynbf.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2826308,
lastWriteDate: 0,
error: MongoNetworkError: connect ETIMEDOUT 52.212.197.12:27017
at connectionFailureError (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:381:20)
at TLSSocket.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at TLSSocket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
},
'cluster0-shard-00-02.0ynbf.mongodb.net:27017' => ServerDescription {
_hostAddress: HostAddress {
isIPv6: false,
host: 'cluster0-shard-00-02.0ynbf.mongodb.net',
port: 27017
},
address: 'cluster0-shard-00-02.0ynbf.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2826318,
lastWriteDate: 0,
error: MongoNetworkError: connect ETIMEDOUT 34.246.79.174:27017
at connectionFailureError (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:381:20)
at TLSSocket.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at TLSSocket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-sujybn-shard-0',
logicalSessionTimeoutMinutes: undefined
}
}
Node.js v17.7.2
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! backendppe#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the backendppe#0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\deyga\AppData\Roaming\npm-cache\_logs\2022-04-04T13_57_51_440Z-debug.log
Complete log of this run
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'start'
1 verbose cli ]
2 info using npm#6.14.15
3 info using node#v14.18.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle backendppe#0.0.0~prestart: backendppe#0.0.0
6 info lifecycle backendppe#0.0.0~start: backendppe#0.0.0
7 verbose lifecycle backendppe#0.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle backendppe#0.0.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Python310\Scripts\;C:\Python310\;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\ProgramData\chocolatey\bin;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Android\android-sdk\platform-tools;C:\Windows\System32\;C:\Users\deyga\AppData\Local\Microsoft\WindowsApps;C:\Users\deyga\AppData\Local\GitHubDesktop\bin;C:\Users\deyga\AppData\Local\Microsoft\WindowsApps;C:\texlive\2020\bin\win32;C:\Users\deyga\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\deyga\AppData\Roaming\npm;C:\Program Files\heroku\bin;C:\Users\deyga\Documents\GitHub\PROJECT_WEB_OCRES;
9 verbose lifecycle backendppe#0.0.0~start: CWD: C:\Users\deyga\Documents\GitHub\PPE\backendPPE
10 silly lifecycle backendppe#0.0.0~start: Args: [ '/d /s /c', 'node ./bin/www' ]
11 silly lifecycle backendppe#0.0.0~start: Returned: code: 1 signal: null
12 info lifecycle backendppe#0.0.0~start: Failed to exec start script
13 verbose stack Error: backendppe#0.0.0 start: `node ./bin/www`
13 verbose stack Exit status 1
13 verbose stack at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack at EventEmitter.emit (events.js:400:28)
13 verbose stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:400:28)
13 verbose stack at maybeClose (internal/child_process.js:1058:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:293:5)
14 verbose pkgid backendppe#0.0.0
15 verbose cwd C:\Users\deyga\Documents\GitHub\PPE\backendPPE
16 verbose Windows_NT 10.0.19043
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v14.18.0
19 verbose npm v6.14.15
20 error code ELIFECYCLE
21 error errno 1
22 error backendppe#0.0.0 start: `node ./bin/www`
22 error Exit status 1
23 error Failed at the backendppe#0.0.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
Message returned in the backend site when I try to access its route: "http://localhost:5000/api/forums"
Not allowed by CORS
Error: Not allowed by CORS
at origin (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\app.js:21:16)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\cors\lib\index.js:199:9)
at corsMiddleware (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\cors\lib\index.js:204:7)
at Layer.handle [as handle_request] (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:323:13)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:341:12)
at next (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\middleware\init.js:40:5)
I use two different ports for my backend server (port 5000) and the frontend (port 3000).
I tried to delete node module in my backend folder and then redo an npm install but it didn't change anything. I also tried to upgrade my npm without result either. I also tried to recover my ip address on https://www.whatismyip.com/ to add it in network access in MongoDB but it did not solve my problem either.
MongoDB Network Access settings
I tried to put as much information as possible about the error but if you find any missing let me know and I will try to add it as soon as possible.
I found several people with the same problem as me on the forums but no solution worked for me, if you could help me it would save me :)

Related

i could'nt connect to mongodb anymore?

in the first try i could connect to my mongodb account at it worked correctly but after 24h hours i couldnt connect anymore at it show me this problem :
>
npm run start
> devconnector#1.0.0 start C:\Users\DELL\Desktop\devconnector
> node server.js
Server running on port 5000
MongoTimeoutError: Server selection timed out after 30000 ms
at Timeout._onTimeout (C:\Users\DELL\Desktop\devconnector\node_modules\mongodb\lib\core\sdam\topology.js:897:9)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
name: 'MongoTimeoutError',
reason: MongoNetworkError: connection 79 to cluster0-shard-00-00-15tsv.mongodb.net:27017
closed
at TLSSocket.<anonymous> (C:\Users\DELL\Desktop\devconnector\node_modules\mongodb\lib\core\connection\connection.js:356:9)
at Object.onceWrapper (events.js:300:26)
at TLSSocket.emit (events.js:210:5)
at net.js:659:12
at TCP.done (_tls_wrap.js:481:7) {
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
},
[Symbol(mongoErrorContextSymbol)]: {}
}
this is my keys.js file : module.exports = {
mongoURI : "mongodb+srv://jassem:<*******>#cluster0-15tsv.mongodb.net/test",
} ;
and this my code to connect to my Mongodb account :
//Connect To mongoDB
mongoose
const express = require ('express') ; const mongoose = require ('mongoose') ;
.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }) .then(()=> console.log('MongoDB connected')) .catch(err => console.log(err)) ;

Unable to connect to remote MySQL database in Node.js application (DOCKER)?

I have NODE.JS application which works with remote MySQL database. In my local computer (windows 10) application successfully connected to remote MySQL database. I use sequelize library for this task. MySQL database has 40 maximum connection pool for each user. When I run this application in Docker which is in CentOS server I notice error. Application raise error when try to connect to remote MySQL database in Docker container. What can be the reason of this problem for your opinion? How I can fix this problem?
ERROR:
Unable to connect to remote MySQL database: { SequelizeConnectionError: connect ETIMEDOUT
at Utils.Promise.tap.then.catch.err (/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:149:19)
at tryCatcher (/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/node_modules/bluebird/js/release/promise.js:690:18)
at _drainQueueStep (/node_modules/bluebird/js/release/async.js:138:12)
at _drainQueue (/node_modules/bluebird/js/release/async.js:131:9)
at Async._drainQueues (/node_modules/bluebird/js/release/async.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (/node_modules/bluebird/js/release/async.js:17:14)
at processImmediate (timers.js:632:19)
name: 'SequelizeConnectionError',
parent:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true },
original:
{ Error: connect ETIMEDOUT
at Connection._handleTimeoutError (/node_modules/mysql2/lib/connection.js:173:17)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true } }
JS:
const Sequelize = require('sequelize');
// "max_user_connections" resource for "db_user" user is "40".
const sequelize = new Sequelize('db_name', 'db_user', 'db_password', {
host: 'HOST',
port: '3306',
dialect: 'mysql',
pool: {
max: 15,
min: 5,
idle: 20000,
evict: 15000,
acquire: 30000
}
});
sequelize.authenticate().then(() => {
console.log('Connection to remote MySQL database has been established successfully.');
}).catch(err => {
console.error('Unable to connect to remote MySQL database:', err);
});
module.exports = sequelize;
Dependencies:
"sequelize": "^4.42.0",
"mysql2": "^1.6.4"

ZeroMQ - Error: Module version mismatch. Expected 46, got 67

While using ZeroMQ messaging in Nodejs getting following error
Error: Module version mismatch. Expected 46, got 67.
at Error (native)
at Object.Module._extensions..node (module.js:435:18)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/home/Documents/HomeApp/node_python/node_modules/zeromq/lib/index.js:6:11)
and here is the code on nodejs server side
app.get("/top", (req, res) => {
console.log("Here0");
res.sendFile(__dirname + "/index.html");
var zerorpc = require("zerorpc");
var client = new zerorpc.Client({ timeout: 3000, heartbeatInterval: 300000 });
console.log("Here");
client.connect("tcp://127.0.0.1:4242");
console.log("And Here");
client.invoke("hello", "World!", function(error, res, more) {
console.log(res);
if (error) {
console.error(error);
}
console.log(tlist);
res.send(tlist);
client.close();
});
node -v = v4.2.6
npm -v = 6.4.1
Tried
"rm -rf node_modules && npm install" still getting same error
"npm install zeromq --build-from-source" didn't work
I'm blocked at this position. Appreciate any help

Express.js app works fine locally but doesn't work when deployed on Heroku

I'm currently trying to deploy a music visualizer that I built. It works in all scenarios except when I click on a song to play from the search bar. I keep on getting '503 (Service Unavailable)'. Does anyone know what's up with my code? I've spent the past 6 hours on SO trying to find the answer, but I've come up with nothing.
Here are my Heroku logs:
2018-08-10T01:47:00.757554+00:00 app[web.1]: events.js:183
2018-08-10T01:47:00.757570+00:00 app[web.1]: throw er; // Unhandled 'error' event
2018-08-10T01:47:00.757572+00:00 app[web.1]: ^
2018-08-10T01:47:00.757573+00:00 app[web.1]:
2018-08-10T01:47:00.757574+00:00 app[web.1]: TypeError: Invalid non-string/buffer chunk
2018-08-10T01:47:00.757576+00:00 app[web.1]: at validChunk (_stream_writable.js:254:10)
2018-08-10T01:47:00.757577+00:00 app[web.1]: at PassThrough.Writable.write (_stream_writable.js:288:21)
2018-08-10T01:47:00.757578+00:00 app[web.1]: at PassThrough.Writable.end (_stream_writable.js:563:10)
2018-08-10T01:47:00.757581+00:00 app[web.1]: at emitThree (events.js:141:20)
2018-08-10T01:47:00.757582+00:00 app[web.1]: at DestroyableTransform.emit (events.js:217:7)
2018-08-10T01:47:00.757583+00:00 app[web.1]: at emitThree (events.js:136:13)
2018-08-10T01:47:00.757585+00:00 app[web.1]: at FfmpegCommand.emit (events.js:217:7)
2018-08-10T01:47:00.757586+00:00 app[web.1]: at emitEnd (/app/node_modules/fluent-ffmpeg/lib/processor.js:424:16)
2018-08-10T01:47:00.757588+00:00 app[web.1]: at /app/node_modules/fluent-ffmpeg/lib/processor.js:433:16
2018-08-10T01:47:00.757589+00:00 app[web.1]: at /app/node_modules/async/dist/async.js:473:16
2018-08-10T01:47:00.765330+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2018-08-10T01:47:00.765674+00:00 app[web.1]: npm ERR! errno 1
2018-08-10T01:47:00.766812+00:00 app[web.1]: npm ERR! yuen#1.0.0 start: `node server.js`
2018-08-10T01:47:00.766955+00:00 app[web.1]: npm ERR! Exit status 1
2018-08-10T01:47:00.767136+00:00 app[web.1]: npm ERR!
2018-08-10T01:47:00.767256+00:00 app[web.1]: npm ERR! Failed at the yuen#1.0.0 start script.
2018-08-10T01:47:00.767393+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2018-08-10T01:47:00.771128+00:00 app[web.1]:
2018-08-10T01:47:00.771274+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2018-08-10T01:47:00.771356+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2018-08-10T01_47_00_768Z-debug.log
Here is the source code for my Express app (server.js):
var express = require('express');
var youtubeStream = require('youtube-audio-stream');
var app = express();
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/stream/:videoId', function (req, res) {
try {
youtubeStream(req.params.videoId).pipe(res);
} catch (exception) {
res.status(500).send(exception);
}
});
app.listen(process.env.PORT || 3000, function () {
console.log('app is listening on port 3000!');
});
Here is the code that actually interacts with the server by sending xhr requests:
function loadSound(vidID) {
context.close()
.then(() => {
context = new AudioContext();
analyser = context.createAnalyser();
analyser.fftSize = 32;
})
.then(() => {
var request = new XMLHttpRequest();
request.open("GET", window.location.href+"stream/"+vidID, true);
request.responseType = "arraybuffer";
request.onload = function() {
var Data = request.response;
process(Data);
};
request.send();
});
}
function process(Data) {
source = context.createBufferSource();
context.decodeAudioData(Data, function(buffer){
source.buffer = buffer;
source.connect(context.destination);
source.connect(analyser);
source.start(context.currentTime);
});
document.getElementById('searchBar').disabled = false;
loading(true);
}
And lastly, here are the listed dependencies in my package.json file:
"dependencies": {
"express": "^4.16.3",
"ffmpeg": "0.0.4",
"fluent-ffmpeg": "^2.1.2",
"through2": "^2.0.3",
"xtend": "^4.0.1",
"youtube-audio-stream": "https://github.com/cryptagoras/youtube-audio-stream/archive/patch-3.tar.gz",
"ytdl-core": "^0.24.0"
}
I found the answer: I didn't actually have any of the encoding libraries installed on Heroku. I simply added ffmpeg into my .buildpacks, and now everything works like a charm!

After successful push to heroku, I get an application error. I am using JAWSdb add-on and mysql on my local. Why cant I get the connection?

Standard express connection
Server.js code:
// Pull in required dependencies
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var port = process.env.PORT || 3000;
var app = express();
// Serve static content for the app from the 'public' directory
app.use(express.static(process.cwd() + '/public'));
app.use(bodyParser.urlencoded({ extended: false }));
// Override with POST having ?_method=DELETE
app.use(methodOverride('_method'));
// Set Handlebars as the view engine
var exphbs = require('express-handlebars');
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
// Import routes and give the server access to them
var routes = require('./controllers/burgers_controller.js');
app.use('/', routes);
app.listen(port);
The connection looks for JAWSdb addon first, if not connect to local
mysql.
Connection.js code:
// Pull in required dependencies
var mysql = require('mysql');
// Create the MySQL connection object
var connection;
if (process.env.JAWSDB_URL) {
// DB is JawsDB on Heroku
connection = mysql.createConnection(process.env.JAWSDB_URL);
} else {
// DB is local on localhost
connection = mysql.createConnection({
port: 3306,
host: 'localhost',
user: 'test',
password: 'test123',
database: 'burgers_db'
})
};
// Make the connection to MySQL
connection.connect(function (err) {
if (err) {
console.error('ERROR: MySQL connection error -- ' + err.stack + '\n\n');
return;
}
console.log('Connected to MySQL database as id ' + connection.threadId + '\n\n');
});
// Export connection for ORM use
module.exports = connection;
I don't think I am missing and dependencies...
package.json code:
{
"name": "eat-da-burger",
"version": "1.0.0",
"description": "Buger eating application with Node.js, Express, Handlebars, and MySQL.",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Hussein Fakhreddine",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"express-handlebars": "^3.0.0",
"method-override": "^2.3.7",
"mysql": "^2.13.0"
}
}
I get an error saying no such table in the logs. I don't know what that means?
Heroku Log:
2018-02-24T23:24:22.364961+00:00 app[web.1]:
2018-02-24T23:24:22.653768+00:00 heroku[web.1]: State changed from starting to up
2018-02-24T23:24:36.540291+00:00 app[web.1]: /app/node_modules/mysql/lib/protocol/Parser.js:80
2018-02-24T23:24:36.540306+00:00 app[web.1]: throw err; // Rethrow non-MySQL errors
2018-02-24T23:24:36.540307+00:00 app[web.1]: ^
2018-02-24T23:24:36.540309+00:00 app[web.1]:
2018-02-24T23:24:36.540310+00:00 app[web.1]: Error: ER_NO_SUCH_TABLE: Table 'blmzyk0sphz3yq4s.burgers' doesn't exist
2018-02-24T23:24:36.540312+00:00 app[web.1]: at Query.Sequence._packetToError (/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
2018-02-24T23:24:36.540314+00:00 app[web.1]: at Query.ErrorPacket (/app/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)
2018-02-24T23:24:36.540315+00:00 app[web.1]: at Protocol._parsePacket (/app/node_modules/mysql/lib/protocol/Protocol.js:279:23)
2018-02-24T23:24:36.540316+00:00 app[web.1]: at Parser.write (/app/node_modules/mysql/lib/protocol/Parser.js:76:12)
2018-02-24T23:24:36.540318+00:00 app[web.1]: at Protocol.write (/app/node_modules/mysql/lib/protocol/Protocol.js:39:16)
2018-02-24T23:24:36.540319+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:103:28)
2018-02-24T23:24:36.540320+00:00 app[web.1]: at emitOne (events.js:116:13)
2018-02-24T23:24:36.540321+00:00 app[web.1]: at Socket.emit (events.js:211:7)
2018-02-24T23:24:36.540323+00:00 app[web.1]: at addChunk (_stream_readable.js:263:12)
2018-02-24T23:24:36.540324+00:00 app[web.1]: at readableAddChunk (_stream_readable.js:250:11)
2018-02-24T23:24:36.540326+00:00 app[web.1]: --------------------
2018-02-24T23:24:36.540327+00:00 app[web.1]: at Protocol._enqueue (/app/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2018-02-24T23:24:36.540328+00:00 app[web.1]: at Connection.query (/app/node_modules/mysql/lib/Connection.js:208:25)
2018-02-24T23:24:36.540329+00:00 app[web.1]: at Object.selectAll (/app/config/orm.js:34:14)
2018-02-24T23:24:36.540330+00:00 app[web.1]: at Object.selectAll (/app/models/burger.js:8:9)
2018-02-24T23:24:36.540331+00:00 app[web.1]: at /app/controllers/burgers_controller.js:10:10
2018-02-24T23:24:36.540333+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2018-02-24T23:24:36.540334+00:00 app[web.1]: at next (/app/node_modules/express/lib/router/route.js:137:13)
2018-02-24T23:24:36.540335+00:00 app[web.1]: at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
2018-02-24T23:24:36.540336+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2018-02-24T23:24:36.540337+00:00 app[web.1]: at /app/node_modules/express/lib/router/index.js:281:22
2018-02-24T23:24:36.547596+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2018-02-24T23:24:36.547898+00:00 app[web.1]: npm ERR! errno 1
2018-02-24T23:24:36.549079+00:00 app[web.1]: npm ERR! eat-da-burger#1.0.0 start: `node server.js`
2018-02-24T23:24:36.549202+00:00 app[web.1]: npm ERR! Exit status 1
2018-02-24T23:24:36.549395+00:00 app[web.1]: npm ERR!
2018-02-24T23:24:36.549506+00:00 app[web.1]: npm ERR! Failed at the eat-da-burger#1.0.0 start script.
2018-02-24T23:24:36.549631+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2018-02-24T23:24:36.559783+00:00 app[web.1]:
2018-02-24T23:24:36.559932+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2018-02-24T23:24:36.560010+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2018-02-24T23_24_36_555Z-debug.log
2018-02-24T23:24:36.544178+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=burgerorder.herokuapp.com request_id=1ffcc0a3-fe15-49a7-80bf-dae378355c0d fwd="172.90.83.64" dyno=web.1 connect=2ms service=18ms status=503 bytes=0 protocol=https
2018-02-24T23:24:36.616665+00:00 heroku[web.1]: State changed from up to crashed
2018-02-24T23:24:36.619541+00:00 heroku[web.1]: State changed from crashed to starting
2018-02-24T23:24:36.604174+00:00 heroku[web.1]: Process exited with status 1
2018-02-24T23:24:39.573704+00:00 heroku[web.1]: Starting process with command `npm start`
2018-02-24T23:24:43.233438+00:00 app[web.1]: Connected to MySQL database as id 48180
2018-02-24T23:24:43.233475+00:00 app[web.1]:
2018-02-24T23:24:43.233478+00:00 app[web.1]:
2018-02-24T23:24:42.532808+00:00 app[web.1]:
2018-02-24T23:24:42.532838+00:00 app[web.1]: > eat-da-burger#1.0.0 start /app
2018-02-24T23:24:42.532845+00:00 app[web.1]: > node server.js
2018-02-24T23:24:42.532846+00:00 app[web.1]:
2018-02-24T23:24:43.889656+00:00 heroku[web.1]: State changed from starting to up
2018-02-24T23:24:45.147650+00:00 app[web.1]: /app/node_modules/mysql/lib/protocol/Parser.js:80
2018-02-24T23:24:45.147675+00:00 app[web.1]: throw err; // Rethrow non-MySQL errors
2018-02-24T23:24:45.147678+00:00 app[web.1]: ^
2018-02-24T23:24:45.147681+00:00 app[web.1]: Error: ER_NO_SUCH_TABLE: Table 'blmzyk0sphz3yq4s.burgers' doesn't exist
2018-02-24T23:24:45.147679+00:00 app[web.1]:
2018-02-24T23:24:45.147684+00:00 app[web.1]: at Query.Sequence._packetToError (/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
2018-02-24T23:24:45.147686+00:00 app[web.1]: at Query.ErrorPacket (/app/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)
2018-02-24T23:24:45.147687+00:00 app[web.1]: at Protocol._parsePacket (/app/node_modules/mysql/lib/protocol/Protocol.js:279:23)
2018-02-24T23:24:45.147689+00:00 app[web.1]: at Parser.write (/app/node_modules/mysql/lib/protocol/Parser.js:76:12)
2018-02-24T23:24:45.147691+00:00 app[web.1]: at Protocol.write (/app/node_modules/mysql/lib/protocol/Protocol.js:39:16)
2018-02-24T23:24:45.147692+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:103:28)
2018-02-24T23:24:45.147694+00:00 app[web.1]: at emitOne (events.js:116:13)
2018-02-24T23:24:45.147697+00:00 app[web.1]: at Socket.emit (events.js:211:7)
2018-02-24T23:24:45.147699+00:00 app[web.1]: at addChunk (_stream_readable.js:263:12)
2018-02-24T23:24:45.147701+00:00 app[web.1]: at readableAddChunk (_stream_readable.js:250:11)
2018-02-24T23:24:45.147703+00:00 app[web.1]: --------------------
2018-02-24T23:24:45.147704+00:00 app[web.1]: at Protocol._enqueue (/app/node_modules/mysql/lib/protocol/Protocol.js:145:48)
2018-02-24T23:24:45.147706+00:00 app[web.1]: at Connection.query (/app/node_modules/mysql/lib/Connection.js:208:25)
2018-02-24T23:24:45.147708+00:00 app[web.1]: at Object.selectAll (/app/config/orm.js:34:14)
2018-02-24T23:24:45.147710+00:00 app[web.1]: at Object.selectAll (/app/models/burger.js:8:9)
2018-02-24T23:24:45.147711+00:00 app[web.1]: at /app/controllers/burgers_controller.js:10:10
2018-02-24T23:24:45.147713+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2018-02-24T23:24:45.147715+00:00 app[web.1]: at next (/app/node_modules/express/lib/router/route.js:137:13)
2018-02-24T23:24:45.147717+00:00 app[web.1]: at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
2018-02-24T23:24:45.147718+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
2018-02-24T23:24:45.147720+00:00 app[web.1]: at /app/node_modules/express/lib/router/index.js:281:22
2018-02-24T23:24:45.162655+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2018-02-24T23:24:45.163528+00:00 app[web.1]: npm ERR! errno 1
2018-02-24T23:24:45.166236+00:00 app[web.1]: npm ERR! eat-da-burger#1.0.0 start: `node server.js`
2018-02-24T23:24:45.166533+00:00 app[web.1]: npm ERR! Exit status 1
2018-02-24T23:24:45.167098+00:00 app[web.1]: npm ERR!
2018-02-24T23:24:45.167408+00:00 app[web.1]: npm ERR! Failed at the eat-da-burger#1.0.0 start script.
2018-02-24T23:24:45.167693+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2018-02-24T23:24:45.183200+00:00 app[web.1]:
2018-02-24T23:24:45.183858+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2018-02-24T23:24:45.184053+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2018-02-24T23_24_45_176Z-debug.log
2018-02-24T23:24:45.156737+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=burgerorder.herokuapp.com request_id=7ba6ffb8-2ba8-45f9-9325-f48155fad950 fwd="172.90.83.64" dyno=web.1 connect=1ms service=50ms status=503 bytes=0 protocol=https
2018-02-24T23:24:45.280176+00:00 heroku[web.1]: State changed from up to crashed
2018-02-24T23:24:45.261501+00:00 heroku[web.1]: Process exited with status 1
2018-02-24T23:25:33.215059+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=burgerorder.herokuapp.com request_id=ed4e8e33-a27d-42ae-8797-82918277154d fwd="172.90.83.64" dyno= connect= service= status=503 bytes= protocol=https
2018-02-24T23:37:19.469262+00:00 heroku[web.1]: State changed from crashed to starting
2018-02-24T23:37:21.346733+00:00 heroku[web.1]: Starting process with command `npm start`
2018-02-24T23:37:22.947106+00:00 app[web.1]:
2018-02-24T23:37:22.947123+00:00 app[web.1]: > eat-da-burger#1.0.0 start /app
2018-02-24T23:37:22.947125+00:00 app[web.1]: > node server.js
2018-02-24T23:37:22.947127+00:00 app[web.1]:
2018-02-24T23:37:23.298062+00:00 app[web.1]: Connected to MySQL database as id 51410
2018-02-24T23:37:23.298091+00:00 app[web.1]:
2018-02-24T23:37:23.298093+00:00 app[web.1]:
2018-02-24T23:37:23.569144+00:00 heroku[web.1]: State changed from starting to up
Adding burgers_controllers.js code:
// Pull in required dependencies
var express = require('express');
var router = express.Router();
// Import the model (burger.js) to use its database functions.
var burger = require('../models/burger.js');
// Create the routes and associated logic
router.get('/', function(req, res) {
burger.selectAll(function(data) {
var hbsObject = {
burgers: data
};
// console.log(hbsObject);
res.render('index', hbsObject);
});
});
router.post('/burgers', function(req, res) {
burger.insertOne([
'burger_name'
], [
req.body.burger_name
], function(data) {
res.redirect('/');
});
});
router.put('/burgers/:id', function(req, res) {
var condition = 'id = ' + req.params.id;
burger.updateOne({
devoured: true
}, condition, function(data) {
res.redirect('/');
});
});
// Export routes for server.js to use.
module.exports = router;
Schema.sql code:**
-- Create the burgers_db database --
CREATE DATABASE
IF NOT EXISTS burgers_db;
USE burgers_db;
-- Create a burgers table with the required fields --
CREATE TABLE burgers
(
id int NOT NULL
AUTO_INCREMENT,
burger_name varchar
(255) NOT NULL,
devoured BOOLEAN DEFAULT false,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP,
dt DATETIME
DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY
(id)
);
orm.js code:
// Import the MySQL connection object
var connection = require ('./connection.js');
// Helper function for generating MySQL syntax
function printQuestionMarks(num) {
var arr = [];
for (var i = 0; i < num; i++) {
arr.push("?");
}
return arr.toString();
}
// Helper function for generating My SQL syntax
function objToSql(ob) {
var arr = [];
for (var key in ob) {
arr.push(key + "=" + ob[key]);
}
return arr.toString();
}
// Create the ORM object to perform SQL queries
var orm = {
// Function that returns all table entries
selectAll: function(tableInput, cb) {
// Construct the query string that returns all rows from the target table
var queryString = "SELECT * FROM " + tableInput + ";";
// Perform the database query
connection.query(queryString, function(err, result) {
if (err) {
throw err;
}
// Return results in callback
cb(result);
});
},
// Function that insert a single table entry
insertOne: function(table, cols, vals, cb) {
// Construct the query string that inserts a single row into the target table
var queryString = "INSERT INTO " + table;
queryString += " (";
queryString += cols.toString();
queryString += ") ";
queryString += "VALUES (";
queryString += printQuestionMarks(vals.length);
queryString += ") ";
// console.log(queryString);
// Perform the database query
connection.query(queryString, vals, function(err, result) {
if (err) {
throw err;
}
// Return results in callback
cb(result);
});
},
// Function that updates a single table entry
updateOne: function(table, objColVals, condition, cb) {
// Construct the query string that updates a single entry in the target table
var queryString = "UPDATE " + table;
queryString += " SET ";
queryString += objToSql(objColVals);
queryString += " WHERE ";
queryString += condition;
// console.log(queryString);
// Perform the database query
connection.query(queryString, function(err, result) {
if (err) {
throw err;
}
// Return results in callback
cb(result);
});
}
};
// Export the orm object for use in other modules
module.exports = orm;
burger.js code:
// Import the ORM to implement functions that will interact with the database
var orm = require('../config/orm.js');
// Create the burger object
var burger = {
// Select all burger table entries
selectAll: function(cb) {
orm.selectAll('burgers', function(res) {
cb(res);
});
},
// The variables cols and vals are arrays
insertOne: function(cols, vals, cb) {
orm.insertOne('burgers', cols, vals, function(res) {
cb(res);
});
},
// The objColVals is an object specifying columns as object keys with associated values
updateOne: function(objColVals, condition, cb) {
orm.updateOne('burgers', objColVals, condition, function(res) {
cb(res);
});
}
};
// Export the database functions for the controller (burgerController.js).
module.exports = burger;
It works when I run the server in node just fine. But when pushed to heroku master the app does not work even after successful push. Am I missing something?
You're using JAWS_DB on Heroku, so you'll have to install the Maria JawsDB add-on and then connect to JawsDB and store your tables/schema there instead of relying on the tables created on your local machine...

Categories