I've been using massive.js within node for a couple months now and never ran into this error. I am completely stumped. Here is the code I am working with:
require('dotenv').config()
const{CONNECTION_STRING, SERVER_PORT, SESSION_SECRET} = process.env
const massive = require('massive')
const express = require('express')
const app = express()
const session = require('express-session')
app.use(express.json())
app.use(session({
resave: true,
saveUninitialized: false,
secret: SESSION_SECRET,
cookie: {
maxAge: 1000 * 60 * 60 * 2
}
}))
massive({
connectionString: CONNECTION_STRING,
ssl: {
rejectUnauthorized: true
}
})
.then(dbInstance => {
app.set('db', dbInstance)
app.listen(SERVER_PORT, () => console.log(`Server is bumping on ${SERVER_PORT}`))
})
.catch(err => console.log(err))
When I run nodemon, I get an error: "Error: self signed certificate". I know it has something to do with massive as when I take it out, nodemon connects to the server. When I change the value of rejectUnauthorized to false I get this error: "TypeError: client.ref is not a function". I have tried running "process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" on the command line and within the code but no luck. Any sort of help would be appreciated.
Related
I am working on to integrate redis, #socket.io/redis-adapter, socket.io and express-session. The following is the code :
// Promisify the methods so we can use async / await with redis
bluebird.promisifyAll(redis);
const redisClient = redis.createClient({ legacyMode: true });
const subClient = redisClient.duplicate({ legacyMode: true });
bluebird.promisifyAll(redisClient);
bluebird.promisifyAll(subClient);
const redisStore = new RedisStore({ client: redisClient });
// Applying Redis middleware
app.use(
session({
secret: process.env.SESSION_SECRET,
// create new redis store.
store: redisStore,
cookie: {
secure: !isDevEnv, // if true: only transmit cookie over https
httpOnly: true, // if true: prevents client side JS from reading the cookie
maxAge: 30 * 24 * 60 * 60 * 1000, // session max age in milliseconds
},
resave: false,
saveUninitialized: true,
rolling: true,
}),
);
In the below code redisClient and subClient are used to pass into createAdapter function . I am using redisClient in another function called IdentityCheck where we use that function to maintain single session for a user and we set the visitorId ( user id) using redis set and get function inside the function IdentityCheck
// Start the server
const server = app.listen(PORT, console.log(`App listening on port: ${PORT}`));
server.setTimeout(6 * 60 * 1000);
// Start socket io with cors enabled
const io = new Server();
io.adapter(adapter.createAdapter(redisClient, subClient));
(async () => {
Promise.allSettled([redisClient.connect(), subClient.connect()]).then(() => {
io.listen(server, {
cors: {
origin: [
'http://localhost:3000'
],
},
transports: ['websocket'],
});
identityCheck.init(io, redisClient); // using redisClient in other file where we use redis get, set methods
redisClient.on('error', (error) => console.error('error from redisClient', error));
subClient.on('error', (error) => console.error('error from subClient', error));
});
})();
Even though I set the error handler as following:
redisClient.on('error', (error) => console.error('error from redisClient', error));
subClient.on('error', (error) => console.error('error from subClient', error));
I still get the missing 'error' handler on this Redis client. Am I doing anything wrong here. I am using the following versions :
{
"express": "^4.17.1",
"express-session": "^1.17.1",
"redis": "4.5.1",
"socket.io": "4.5.4",
"socket.io-client": "4.5.4",
"#socket.io/redis-adapter": "8.0.1",
}
redis version 4.5.1, socket.io, socket.io-client-4.5.4 and #socket.io/redis-adapter": "8.0.1",
I downgraded the redis version to 3.1.2 and the error has gone! I think there's something to do with redis version 4 . If anyone has correct reason please feel free to answer. thanks
I am creating a site using Node.js, React, Vite, Knex.js and PostgreSQL and have run into an error when trying to start up my server and connect to my database which I don't know how to solve. I have looked around elsewhere online, which also hasn't been much help. Here are what the relevant files look like:
server.js
const express = require('express');
const PATH = 5000;
const app = express();
const cors = require('cors');
const session = require('./db/session');
const { passport } = require('./passport');
app.use(cors({
origin: process.env.VITE_CORS_ORIGIN,
credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session);
app.use(passport.initialize());
app.use(passport.session());
app.use(require('./routes'));
app.use(function(req, res, next) {
res.status(404).send("Unable to find requested resource.")
});
app.use((err, req, res, next) => {
if (err) {
req.logout();
next();
}
res.status(err.status || 500).send(err.message);
});
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`)
});
knexfile.js
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '.env.development') });
const dbMode =
process.env.VITE_ENV === 'development' ? {
client: "pg",
connection: {
host: 'localhost',
port: 5432,
user: process.env.VITE_DB_USER,
password: process.env.VITE_DB_PASS,
database: process.env.VITE_DB_NAME,
charset: 'utf8'
},
migrations: {
directory: './server/db/migrations',
tableName: "knex_migrations"
},
seeds: {
directory: './server/db/seeds'
},
} : {
client: "pg",
connection: process.env.DATABASE_URL,
ssl: { require: true }
}
module.exports = dbMode;
db.js
const knex = require('knex');
const dbConfig = require('../../knexfile');
const db = knex(dbConfig);
module.exports = db;
I also have a session store set up using express-session and connect-pg-simple. I also use Passport.js.
Whenever I try start the server ('node initServer.js') I get the error message:
<project path>/node_modules/pg/lib/sasl.js:24
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string'
I have made sure that all my environment variables are working and are the right type. I have used console.log() to confirm that the variables aren't undefined and used typeof to confirm that the type of the environment variable for the DB password is a string.
I am using the same password details and postgreSQL installation as I used for another recent project, so I am sure that the password is not wrong and that all the details are correct.
I have no idea what I need to do to fix this as the password is (as far as I can tell) being passed correctly. I'd really appreciate your help.
If there's anything you'd like me to show or explain to help you solve this, please let me know.
Couple days I had this same issue running the knex migrate:list cli command. Checking your example, you are doing as the same way I had before. So testing changes and reading the knex documentation I reached to conclusion that:
Its seems like the knex-cli not reading the values from the
environment variables
If you still have the issue, these are the steps I follow to fixed it
1. What I did to be sure that the knex-cli was reading the environments variables, I add the client config as static string values. This will validate the reading variable issue.
2. Instead of using path lib and __dirname, I just used the relative path.
3. I tested the fix, running the knex migrate:list, and its work for me.
Maybe you others alternative of solution, but if you reach to fix the issue in ad different way please share it as a comment, so we can exchange knowledge and see a different way how to solve this issue.
Regards
I found a solution, though I am not entirely sure why this was necessary given that in projects I have done in the past this step was not required in order to connect to my database.
It turns out that the issue was connected to my session.js file. By adding the database connection object from my knexfile to express-session as follows, I was able to get around this error:
const path = require('path');
const connection = require('../../knexfile');
require('dotenv').config({ path: path.join(__dirname, '..', '..', '.env.development') });
const express_session = require('express-session');
const pgSession = require('connect-pg-simple')(express_session);
const theSecret = process.env.VITE_SESSION_SECRET;
const session = express_session({
store: new pgSession({ tableName: 'sessions', conObject: connection }),
secret: theSecret,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 }
})
module.exports = session;
Admittedly, I actually still have another issue despite doing this. Though I can now actually run my server, for some reason I also get the below message:
Failed to prune sessions: con.connect is not a function
I will make a separate question about this.
Working on a backend using nodejs, express, express-session, cors & cookie-parser to communicate with a react app that use axios to send http request, and using mariadb for the database.
Using both of them on localhost (3000 front end, 3001 backend) work fine, session is correctly saved and can be retrieved / used (I just pass the user data).
When deploying the backend on either local network or an EC2 instance from aws, the req.session return only the parameters set on "cookies" in the app.use(session({}) when called after being set on the login.
app.js:
const express = require('express');
const cors = require('cors');
const session = require('express-session');
const pool = require('./config/database');
const cookieParser = require('cookie-parser');
const app = express();
app.use(express.json());
app.use(cors(
{
credentials: true,
origin: true,
}
));
app.set('trust proxy', 1)
app.use(cookieParser());
app.use(session({
secret: 'cat on keyboard',
saveUninitialized: false,
resave: false,
cookie: { httpOnly: false, maxAge: 1000 * 60 * 60 * 24 }
}));
The req.session set
getAccountIdByEmail: async (req, res) => {
// connect & retrieve user from credentials //
req.session.logged_user = user[0][0];
return res.status(200).json({ success: user[0][0] })
};
The axios call from react app:
const fetchData = () => {
if (adress.charAt(0) == '/') {
adress = endpoint + adress;
}
axios({
method: method,
url: adress,
data: content,
withCredentials: true
})
.then((res) => {
setResponse(res.data);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setloading(false);
});
};
At first i thougt it came from Nginx on Aws EC2, but it does the same calling directly on port 3001 of the instance, then i had the same issue on a local network.
I've tried also to use a store (express-session-mariadb-store or express-mysql-session), without success.
I think it might be tied to cors or headers, but couldn't pinpoint what doesn't work.
I noticed on express-session-npm
there is a disclaimer saying it is only for development and will have memory leaks if deployed in production
So, I have just added Redis to my expressjs app (this is the first time I use redis), and this is all I did to add the Redis:
import express, { Application } from 'express';
import session from 'express-session';
import {createClient} from 'redis';
import connectRedis from 'connect-redis'
const app: Application = express();
const RedisStore = connectRedis(session);
const redisClient = createClient({
url: 'redis://localhost:6379'
});
app.use(session({
secret: SESSION_SECRET,
resave: false,
saveUninitialized: true,
store: new RedisStore({ client: redisClient }), // added this line
cookie: {
maxAge: 1000 * 60 * 2,
httpOnly: false,
secure: false,
}
}));
export default app;
But when I make any request to any of my express routes, I get an instant error on console, and the app is closed for any further requests. This is the error:
As you can see, there is a line Server is listening on port 3000 at the top of the screenshot, the rest of the strings appears only when I make the first request to the api.
What am I missing here, what did I do wrong? Because every video/article on internet has the same exact code...
Well, as noticed by #Apoorva Chikara and mentioned by #Leibale Eidelman , connect-redis does not support latest node-redis yet, so to fix it I just downgraded my redis package to the version 3.1.2 by using $ yarn add redis#3.1.2.
Thanks!
This is my code for mongodb atlas connection, it shows connection successful but later when I click on some tab the app crashes. I m deploying app through heroku and i have given the error below .app runs fine on localhost but crashes on the heroku website. It sometimes allows and opens some pages but crashes right after that , i have tried fixing environemnt variables on heroku website but that was of no help so i switched to just using the mongo connection link through the variable. Any help is appreciated.
I discovered that the server throws the error of not being able to connect after exactly 30 seconds but still cant find what is causign the error
if (process.env.NODE_ENV !== "production") {
require('dotenv').config();
}
const sanitize = require('express-mongo-sanitize');
// const dbURL = process.env.DB_URL;
const session = require('express-session');
const MongoStore = require('connect-mongodb-session')(session);
const dbURL = "mongodb+srv://RohanGupta:****************#*****.****.mongodb.net/oddevegame?retryWrites=true&w=majority";
mongoose.connect(dbURL, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => {
console.log("Connected Mongo Successfully")
})
.catch(err => {
console.log("Uh Oh couldnt connect mongo!!")
console.log(err);
})
app.use(methodOverride('_method'));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.static(path.join(__dirname, '/resources')));
app.use(session({
store: new MongoStore({
url: dbURL,
touchAfter: 24 * 3600
}),
name: "blah",
secret: 'this is secret',
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
// secure: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}));
2021-06-20T07:27:23.462279+00:00 heroku[web.1]: State changed from starting to up
2021-06-20T07:27:23.230556+00:00 app[web.1]: Listening on PORT 4000
2021-06-20T07:27:23.502833+00:00 app[web.1]: Connected Mongo Successfully
2021-06-20T07:27:53.221633+00:00 app[web.1]: /app/node_modules/mongodb/lib/utils.js:698
2021-06-20T07:27:53.221654+00:00 app[web.1]: throw error;
2021-06-20T07:27:53.221655+00:00 app[web.1]: ^
2021-06-20T07:27:53.221655+00:00 app[web.1]:
2021-06-20T07:27:53.221656+00:00 app[web.1]: Error: Error connecting to db: connect ECONNREFUSED 127.0.0.1:27017
2021-06-20T07:27:53.221656+00:00 app[web.1]: at /app/node_modules/connect-mongodb-session/index.js:78:17