admin管理员组

文章数量:1200363

I have a node.js express app with session and redis. It seems to be working so far.

In case the redis connection fails, e.g. wrong url or password, I would like to switch the 'store' parameter in app.use(session()) to false and to the default memoryCache, how can I accomplish this since the server and session settings always are created before the redis .connect() is finished. How would I need to change my setup?

Error:

Server running at http://127.0.0.1:2002/
error
Error: connect ECONNREFUSED 127.0.0.2:6379
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1605:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.2',
  port: 6379
}

App (index.js):

const { RedisStore } = require('connect-redis');
const { createClient } = require('redis');

const express = require('express');
const session = require('express-session');

...

let client = createClient({ url: 'MY_URL', password: 'MY_PW' });

var session_store = new RedisStore({ client: client });

(async () => {
  try {
    await client.connect();
    await client.ping();
  } catch (error) {
    console.error('error');
    console.error(error);
  }
})();

const app = express();

...

app.use(session({
  store: session_store,
  //store: false,
  secret: 'MY_SECRET',
  key: 'MY_KEY',
  resave: false,
  saveUninitialized: false,
  cookie: cookie_config
}));

...

module.exports = app;

const server = http.createServer(app);

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Setup:

node.js v20.12.1

"connect-redis": "^8.0.1",
"express": "^4.18.2",
"express-session": "^1.17.3",
"redis": "^4.7.0",

本文标签: Nodejs ExpressRedis connect error handlingStack Overflow