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.
Related
this is my command prompt:
2022-07-10T23:36:17.323791+00:00 heroku[web.1]: Process exited with status 1
2022-07-10T23:36:17.574484+00:00 heroku[web.1]: State changed from up to crashed
2022-07-10T23:36:17.578331+00:00 heroku[web.1]: State changed from crashed to starting
2022-07-10T23:36:19.862639+00:00 heroku[web.1]: Starting process with command `node server`
2022-07-10T23:36:21.568790+00:00 app[web.1]: Server running in development mode on port 52222
2022-07-10T23:36:22.148988+00:00 heroku[web.1]: State changed from starting to up
2022-07-10T23:36:51.593762+00:00 app[web.1]: MongooseServerSelectionError: connection <monitor> to 104.155.184.217:27017 closed
2022-07-10T23:36:51.593769+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:819:32)
2022-07-10T23:36:51.593771+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:378:10
2022-07-10T23:36:51.593773+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
2022-07-10T23:36:51.593773+00:00 app[web.1]: at new Promise (<anonymous>)
2022-07-10T23:36:51.593774+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
2022-07-10T23:36:51.593774+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1223:10)
2022-07-10T23:36:51.593774+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:377:20)
2022-07-10T23:36:51.593775+00:00 app[web.1]: at connectDB (/app/config/db.js:6:37)
2022-07-10T23:36:51.593775+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:10:1)
2022-07-10T23:36:51.593775+00:00 app[web.1]: at Module._compile (node:internal/modules/cjs/loader:1105:14) {
2022-07-10T23:36:51.593776+00:00 app[web.1]: reason: TopologyDescription {
2022-07-10T23:36:51.593777+00:00 app[web.1]: type: 'ReplicaSetNoPrimary',
2022-07-10T23:36:51.593777+00:00 app[web.1]: servers: Map(3) {
2022-07-10T23:36:51.593778+00:00 app[web.1]: 'ac-eqnecmx-shard-00-00.uqxpgna.mongodb.net:27017' => [ServerDescription],
2022-07-10T23:36:51.593778+00:00 app[web.1]: 'ac-eqnecmx-shard-00-01.uqxpgna.mongodb.net:27017' => [ServerDescription],
2022-07-10T23:36:51.593778+00:00 app[web.1]: 'ac-eqnecmx-shard-00-02.uqxpgna.mongodb.net:27017' => [ServerDescription]
2022-07-10T23:36:51.593779+00:00 app[web.1]: },
2022-07-10T23:36:51.593779+00:00 app[web.1]: stale: false,
2022-07-10T23:36:51.593780+00:00 app[web.1]: compatible: true,
2022-07-10T23:36:51.593780+00:00 app[web.1]: heartbeatFrequencyMS: 10000,
2022-07-10T23:36:51.593780+00:00 app[web.1]: localThresholdMS: 15,
2022-07-10T23:36:51.593781+00:00 app[web.1]: setName: 'atlas-qcim0h-shard-0',
2022-07-10T23:36:51.593781+00:00 app[web.1]: logicalSessionTimeoutMinutes: undefined
2022-07-10T23:36:51.593781+00:00 app[web.1]: },
2022-07-10T23:36:51.593781+00:00 app[web.1]: code: undefined
2022-07-10T23:36:51.593781+00:00 app[web.1]: }
2022-07-10T23:36:51.889734+00:00 heroku[web.1]: Process exited with status 1
2022-07-10T23:36:51.942371+00:00 heroku[web.1]: State changed from up to crashed
2022-07-10T23:47:28.294565+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=pomoworko.herokuapp.com request_id=f70e80ad-c7f4-475d-b830-1b1cad21a5cc fwd="181.56.0.86" dyno= connect= service= status=503 bytes= protocol=https
this is my code:
Procfile:
web:node server
.gitignore:
node_modules/
server.js
const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const connectDB = require('./config/db')
const passport = require('passport')
const bodyParser = require('body-parser')
const routes = require('./routes/index')
connectDB()
const app = express()
if(process.env.NODE_ENV === 'development') {
app.use(morgan('dev'))
}
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(routes)
app.use(passport.initialize())
require('./config/passport')(passport)
const PORT = process.env.PORT || 3000
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`))
package.json:
{
"name": "flutterauth",
"version": "1.0.0",
"description": "Authentication system for flutter apps",
"main": "server.js",
"scripts": {
"start": "cross-env NODE_ENV=production node server",
"dev": "cross-env NODE_ENV=development nodemon server"
},
"author": "pomoworko",
"license": "MIT",
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "^1.20.0",
"connect-mongo": "^4.6.0",
"cors": "^2.8.5",
"cross-env": "^7.0.3",
"express": "^4.18.1",
"jwt-simple": "^0.5.6",
"mongoose": "^6.4.4",
"morgan": "^1.10.0",
"nodemon": "^2.0.19",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0"
}
}
For now, I got this:
If I write on the command prompt: "heroku restart", It works
And if I write on the command prompt: "heroku logs --tail", it shows me again, the first image, it doesn't work
How to fix this error
Thank you in advance
I'm assuming you are using mongodB atlas. You need to whitelist your IP address. To do that, head over to your network access tab, and include an IP address 0.0.0.0/0. This is a wild card IP address that would allow all IP addresses with the correct credentials to access your DB.
As such:
Note: This whitelists all IP addresses. It's alright when testing. But when going into production, you might want to whitelist only IP addresses that should have access to the cluster...for security purposes.
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?
My post request to create new item, turns me with new item created. It is working well in localhost.
But when I deploy my app on heroku and then post request Status Code: 503 Service Unavailable , but empty res.body. Here also my server.js file
server.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const app = express();
const items = require("./routes/api/items");
const users = require("./routes/api/user");
const auth = require("./routes/api/auth");
app.use(express.json());
require("dotenv").config();
mongoose.connect(process.env.MONGO_DB).then(console.log("connected"));
app.use(cors());
app.use("/api/items", items);
app.use("/api/users", users);
app.use("/api/auth", auth);
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
const listener = app.listen(process.env.PORT || 5000, () => {
console.log("Your app is listening on port " + listener.address().port);
});
item.js
router.post("/createTeam", auth, (req, res) => {
const newItem = new Item({
name: req.body.name,
});
newItem.save(function (err, result) {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
itemActions.js
export const addItems = (input) => (dispatch, getState) => {
axios
.post("/api/items/createTeam", input, tokenConfig(getState))
.then((res) =>
dispatch({
type: ADD_ITEM,
payload: res.data,
})
)
.catch((err) =>
dispatch(
returnErrors(err.response.data, err.response.status, "GET_ERRORS")
)
);
};
Also my heroku logs are here when I create new Team
2021-12-04T09:51:55.743015+00:00 app[web.1]: MongoWriteConcernError: No write concern mode named 'majority\"' found in replica set configuration
2021-12-04T09:51:55.743023+00:00 app[web.1]: at MessageStream.messageHandler (/app/node_modules/mongodb/lib/cmap/connection.js:463:30)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at MessageStream.emit (events.js:400:28)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at processIncomingData (/app/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
2021-12-04T09:51:55.743024+00:00 app[web.1]: at MessageStream._write (/app/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
2021-12-04T09:51:55.743025+00:00 app[web.1]: at writeOrBuffer (internal/streams/writable.js:358:12)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at MessageStream.Writable.write (internal/streams/writable.js:303:10)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at TLSSocket.ondata (internal/streams/readable.js:731:22)
2021-12-04T09:51:55.743026+00:00 app[web.1]: at TLSSocket.emit (events.js:400:28)
2021-12-04T09:51:55.743027+00:00 app[web.1]: at addChunk (internal/streams/readable.js:293:12)
2021-12-04T09:51:55.743027+00:00 app[web.1]: at readableAddChunk (internal/streams/readable.js:267:9) {
2021-12-04T09:51:55.743028+00:00 app[web.1]: code: 79,
2021-12-04T09:51:55.743030+00:00 app[web.1]: codeName: 'UnknownReplWriteConcern',
2021-12-04T09:51:55.743030+00:00 app[web.1]: errInfo: {
2021-12-04T09:51:55.743031+00:00 app[web.1]: writeConcern: { w: 'majority"', wtimeout: 0, provenance: 'clientSupplied' }
2021-12-04T09:51:55.743031+00:00 app[web.1]: },
2021-12-04T09:51:55.743032+00:00 app[web.1]: result: {
2021-12-04T09:51:55.743032+00:00 app[web.1]: n: 1,
2021-12-04T09:51:55.743032+00:00 app[web.1]: opTime: { ts: new Timestamp({ t: 1638611515, i: 13 }), t: 104 },
2021-12-04T09:51:55.743033+00:00 app[web.1]: electionId: new ObjectId("7fffffff0000000000000068"),
2021-12-04T09:51:55.743033+00:00 app[web.1]: ok: 1,
2021-12-04T09:51:55.743034+00:00 app[web.1]: writeConcernError: {
2021-12-04T09:51:55.743034+00:00 app[web.1]: code: 79,
2021-12-04T09:51:55.743034+00:00 app[web.1]: codeName: 'UnknownReplWriteConcern',
2021-12-04T09:51:55.743035+00:00 app[web.1]: errmsg: `No write concern mode named 'majority\\"' found in replica set configuration`,
2021-12-04T09:51:55.743035+00:00 app[web.1]: errInfo: [Object]
2021-12-04T09:51:55.743036+00:00 app[web.1]: },
2021-12-04T09:51:55.743036+00:00 app[web.1]: '$clusterTime': {
2021-12-04T09:51:55.743036+00:00 app[web.1]: clusterTime: new Timestamp({ t: 1638611515, i: 13 }),
2021-12-04T09:51:55.743036+00:00 app[web.1]: signature: [Object]
2021-12-04T09:51:55.743037+00:00 app[web.1]: },
2021-12-04T09:51:55.743037+00:00 app[web.1]: operationTime: new Timestamp({ t: 1638611515, i: 13 })
2021-12-04T09:51:55.743037+00:00 app[web.1]: }
2021-12-04T09:51:55.743037+00:00 app[web.1]: }
SOLUTION
I removed '' or "" from MONGO_DB which is on heroku config vars, and solved
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
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.