I am trying to use connect-mongo to store my express-session's however I am getting a depreciation warning on my server, but not my development machine.
The server is running Ubuntu 16.04, node v8.9.3
My dev machine is windows, node v8.9.4
the codebase is identicle. however on my server I am getting the following messages:
(node:1789) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: cyclic dependency detected
(node:1789) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I admit I am a novice when it comes to node.
this is the code I am using:
const express = require('express');
const path = require('path');
const expressSession = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(expressSession);
//Custom Modules Declarations
const settings = require('./config/app-settings');
//Open Connection to MongoDB
const connection = mongoose.createConnection(settings.settings.databaseUri);
//App Setup
const app = express();
// Express session
app.use(expressSession({
secret: 'secret',
//cookie: {maxAge: config.mongoDBSessionMaxAge * 1000},
resave: true,
saveUninitialized: true,
store: new MongoStore({
mongooseConnection: connection,
clear_interval: settings.settings.mongoDBSessionMaxAge
})
}));
please could you help me to remove the errors?
Related
Current development environment is as follows
Windows 11 Home-64bit
GCP Computer Instance: Ubuntu 20.04.5 LTS
Situation Description
Express.js + Sequelize is being used, and in the case of DB, GCP's Cloud SQL is being used.
In the local environment, it is determined that there is no problem because it is linked to Cloud SQL and reflected immediately when operated in MySQL Workbench.
Attempt to run a backend project through a GCP computer instance and verify that it works like local even in deployment.
Errors that have never been seen in a local environment are output.
DB access error and express.session error occur, but I don't understand why this error occurs only in the distribution version, and this error did not occur at all in the development version.
Error message output from GCP
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'#'localhost' (using password: NO)",
sql: undefined
}
express-session deprecated req.secret; provide secret option at app.js:34:9
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const dotenv = require('dotenv');
const cors = require('cors')
dotenv.config();
const AlphaRoute = require('./Routes/Alpha')
const AuthRouter = require('./Routes/Auth')
const {sequelize} = require('./models')
const app = express();
app.set('PORT', process.env.PORT || 8095);
sequelize.sync({force: false})
.then(() => {console.log('db ok')})
.catch((err) => {console.error(err)})
app.use(cors({
origin: '*'
}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(session({
resave: false,
saveUninitialized: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true,
secure: false,
},
}));
app.use('/auth', AuthRouter)
app.use('/alpha', AlphaRoute)
app.listen(app.get("PORT"), () => {
console.log(app.get("PORT"), 'Online')
})
The way I tried it.
In the case of DB access error, the password input part of config.js was set to process.env.DB_PASSWORD, but as the problem continued, we changed it to input the password string.
Is it a problem that occurs because the password of the DB is not unified? I unified it with the Root password when CloudSQL was created.
What code should I modify to solve this problem?
I have completed a project and trying to deploy on heroku. I am using Reactjs frontend and express Nodejs with mongoose and mongodb in the Backend. It works on localhost but when I run Build it and try to deploy it on heroku it gives an application error.
Here is my backend connection code:
require('dotenv').config();
const express = require('express')
const session = require("express-session")
const bodyParser = require('body-parser')
const cors = require('cors')
const zomatoRoutes = require('./Routes/zomato')
const paymentRoutes = require('./Routes/payments')
const mongoose = require('mongoose')
const passport = require("passport")
const MongoStore = require('connect-mongo');
const uri = process.env.MONGO_URI || 'mongodb://localhost/zomato';
console.log(uri,'this is the mongo Atlas uri if connected using that !!!')
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName:'zomato1'
}
const connectDB = async () => {
await mongoose.connect(uri, options ).then(() => {
console.log('mongo connected')
}).catch( e => console.log(e))
}
connectDB().then(() => {
app.listen( process.env.PORT ||5252 , () => {
console.log("express app is up and running on port 5252");
})
})
I also have mongo session store the mongoose session when user logs in
app.use(session({
secret: "this is unambigous secret",
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24*60*60*1000 },
store : MongoStore.create({
client: mongoose.connection.getClient(),
dbName:'zomato1',
ttl: 14 * 24 * 60 * 60
})
}));
app.use(passport.initialize());
app.use(passport.session());
It gives me MongoNotConnectedError: MongoClient must be connected to perform this operation error when I try to deploy using
git push heroku master:main
full error tail :
mongodb+srv://vishal_torne_22:********#db-first-hernode.zu6btrs.mongodb.net/<DBNamecomeshere>?retryWrites=true&w=majority this is the mongo Atlas uri if connected using that !!!
2022-07-31T11:19:34.581869+00:00 app[web.1]: /app/node_modules/mongodb/lib/utils.js:367
2022-07-31T11:19:34.581876+00:00 app[web.1]: throw new error_1.MongoNotConnectedError('MongoClient must be connected to perform this operation');
2022-07-31T11:19:34.581877+00:00 app[web.1]: ^
2022-07-31T11:19:34.581877+00:00 app[web.1]:
2022-07-31T11:19:34.581878+00:00 app[web.1]: MongoNotConnectedError: MongoClient must be connected to perform this operation
2022-07-31T11:19:34.581878+00:00 app[web.1]: at getTopology (/app/node_modules/mongodb/lib/utils.js:367:11)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at Collection.createIndex (/app/node_modules/mongodb/lib/collection.js:258:82)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at MongoStore.setAutoRemove (/app/node_modules/connect-mongo/build/main/lib/MongoStore.js:147:35)
2022-07-31T11:19:34.581881+00:00 app[web.1]: at /app/node_modules/connect-mongo/build/main/lib/MongoStore.js:128:24
2022-07-31T11:19:34.581882+00:00 app[web.1]: at processTicksAndRejections (node:internal/process/task_queues:96:5)
2022-07-31T11:19:34.581882+00:00 app[web.1]:
2022-07-31T11:19:34.581882+00:00 app[web.1]: Node.js v17.9.1
2022-07-31T11:19:34.703486+00:00 heroku[web.1]: Process exited with status 1
2022-07-31T11:19:34.791551+00:00 heroku[web.1]: State changed from starting to crashed
I am using Mongoose to connect the Mongodb, It works on localhost without heroku but when I deploy it using heroku, It asks me to use MongoClient. Is it a requirement to use mongoClient on Heroku 20 stack, I also get warning to upgrade to new Heroku version, I tried to upgrade heroku using npm upgrade heroku to the specifed version it shows successful but again rolls back to heroku 20 stack.
here's what I tried but researching the previous answers :
I added on my mongodb atlas the whitelist 0.0.0.0/0 (includes you current IP address)
I tried to make the mongoose code async so that it connect firsts the database then app listens to the port.
changed the engine version so that it supports latest node and npm version on Heroku like:
{
"version": "1.0.0",
"engines": {
"node": "17.x",
"npm":"8.x"
}
}
Is it a requirement to use MongoClient on heroku 20 stack ? as the Error shows... and why it is showing error on Mongoose.connect()
Thanks in advance..!
As you say it runs fine in your local environment, the issue may be fixed by adding process.env.MONGO_URL to the config vars of your application, as the issue may originate when Heroku tries to connect to your MongoDB, but does not achieve this connection due to an invalid url that is stored in an env variable on your local device.
I am trying to connect to my database on MongoDB Atlas using mongoose. But every time it's giving me the following error:
(node:2327) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT cluster0-abjwg.gcp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:206:19)
(node:2327) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2327) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have tried whitelisting the IP. Also, the same code is working fine on another machine but not on my machine.
The code is:
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
// Connecting to MongoDB
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log('Connection established');
})
app.use(express.json());
app.listen(port, () => {
console.log(`Here we go on port: ${port}`);
});
It is supposed to give output:
Here we go on port: 5000
Connection established
But I'm getting the only the first output and the error.
DNS resolution for TXT records appears to be broken on your machine. You can use the legacy URI (the one without srv) to connect instead.
My Internet Service Provider was blocking the connection. I changed my DNS to Google's Public DNS and the error was no more. I followed the link below to change my DNS.
https://developers.google.com/speed/public-dns/docs/using
I am getting the error message deprecated body-parser i've looked up other methods concerning parsing the data but none seem to work. the below code what ive got
const express = require('express');
const app = express();
const Task = require('./api/models/ListModels.js'); //created model loading here
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const routes = require('./api/routes/ListRoutes.js'); //importing route
routes(app); //register the route
app.listen(3000, () => {
console.log('running on 3000')
})
The error:
PS C:\Users\demar\Desktop\New folder\ListAPI> node app.js
(node:10424) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
running on 3000
(node:10424) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\topologies\server.js:562:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\connection\pool.js:316:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (C:\Users\demar\Desktop\New folder\ListAPI\node_modules\mongodb-core\lib\connection\connection.js:245:50)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
(node:10424) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without
a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10424) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
It honestly tells you what to do..
To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
I added the options and it works perfectly..
Originally:
// Connect to Mongo:
mongoose.connect(db).then(() => console.log("Mongo DB Connected")).catch(err => console.log(err));
Current:
// Connect to Mongo:
mongoose.connect(db, { useNewUrlParser: true}).then(() => console.log("Mongo DB Connected")).catch(err => console.log(err));
This fixed the issue
The error is that your version of Node's URL string parser, that Mongoose is using, is deprecated.
Pass in the option {useNewUrlParser: true} to mongoose.connect() to use the new Node Core URL API.
mongoose.connect('mongodb://localhost/Tododb', {useNewUrlParser: true})
That error is appearing because you didn't specified the port number mongodb is running on.
mongoose.connect('mongodb://localhost:27017/databasename', { useNewUrlParser: true })
this will fix your issue :)
Yes, body-parser has been deprecated.
Don't use it anymore
Since Express 4.16+ the body parsing functionality has become built into express
You can do
app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads
From directly express, without having to install body-parser.
so you can uninstall body-parser using npm uninstall body-parser, and simply use the above code from express.
I'm new to node and I'm pretty sure I've set up the middle ware and express to use flash messaging however I still get the error:
Error: req.flash() requires sessions
Setup
//express.js
var flash = require('connect-flash')
module.exports = function (app, config, passport) {
app.use(flash());
};
//route js
exports.loginGet = function (req, res) {
res.render('users/login', {
title: 'Login',
message: req.flash('error') //error in question
});
};
What else can I do to make sure I have everything set up correctly and get it working?
From the readme (emphasis mine):
Flash messages are stored in the session. First, setup sessions as usual by enabling cookieParser and session middleware. Then, use flash middleware provided by connect-flash.
Using express-sessions with express 4, cookieParser is no longer required.
var session = require('express-session');
//...
app.use(session({ cookie: { maxAge: 60000 },
secret: 'woot',
resave: false,
saveUninitialized: false}));
In my case the issue was that Redis was not listening. I found that out by enabling the logErrors property:
new RedisStore({
host: 'localhost',
port: '6379',
logErrors: true,
});
Which resulted in messages like these:
Warning: connect-redis reported a client error: Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
Please check mongodb connections. there may be an mongo error like "mongoError: Topology was destroyed".
To fix this issue, check here
i was having these issues and I solve them by respecting the cascading
app.use(passport.initialize());
app.use(passport.session());
//SESSION FLASH
app.use(flash());