admin管理员组

文章数量:1402945

I'm implementing Access Token and Refresh Token using JWT for login function in NodeJS application. I'm trying to use Redis to store the Refresh Token, but I'm getting the following code :

redis.js

const redis = require('redis');

require('dotenv').config({ path : __dirname + '/../config/env/.env' });

let redisClient;

redisClient = redis.createClient(6379, '127.0.0.1');

module.exports = redisClient;

authRoute.js

'use strict';

const JwtUtil     = require('../../middlewares/jwt-util');
const redisClient = require('../../middlewares/redis');

const authRouter = require('express').Router();

const jwt = new JwtUtil(); 

authRouter.post('/user-token/generate', (req, res, next) => {
    const accessToken = jwt.sign(req.body);

    const refreshToken = jwt.refresh();

    redisClient.set(req.body.id, refreshToken);

    res.status(200).send({
        result : 'success',
        data : {
            accessToken,
            refreshToken
        }
    });
});

module.exports = authRouter;

I have printed several logs, but it seems that redisClient.set(req.body.id, refreshToken); in authRoute.js. There seems to be an error in.

UnhandledPromiseRejectionWarning: Error: The client is closed

(node:24640) 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 .html#cli_unhandled_rejections_mode). (rejection id: 2) (node:24640) [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.

Access Token and Refresh Token are issued normally. Also, the following code doesn't work. I'm not sure how I should rewrite the code. What should I do?

redisClient.on('connection', () => { 
  console.info('Redis connected!');
}

Although I'm using the Windows, I downloaded Redis, performed a ping test, and confirmed that the server is running.

I'm implementing Access Token and Refresh Token using JWT for login function in NodeJS application. I'm trying to use Redis to store the Refresh Token, but I'm getting the following code :

redis.js

const redis = require('redis');

require('dotenv').config({ path : __dirname + '/../config/env/.env' });

let redisClient;

redisClient = redis.createClient(6379, '127.0.0.1');

module.exports = redisClient;

authRoute.js

'use strict';

const JwtUtil     = require('../../middlewares/jwt-util');
const redisClient = require('../../middlewares/redis');

const authRouter = require('express').Router();

const jwt = new JwtUtil(); 

authRouter.post('/user-token/generate', (req, res, next) => {
    const accessToken = jwt.sign(req.body);

    const refreshToken = jwt.refresh();

    redisClient.set(req.body.id, refreshToken);

    res.status(200).send({
        result : 'success',
        data : {
            accessToken,
            refreshToken
        }
    });
});

module.exports = authRouter;

I have printed several logs, but it seems that redisClient.set(req.body.id, refreshToken); in authRoute.js. There seems to be an error in.

UnhandledPromiseRejectionWarning: Error: The client is closed

(node:24640) 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/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2) (node:24640) [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.

Access Token and Refresh Token are issued normally. Also, the following code doesn't work. I'm not sure how I should rewrite the code. What should I do?

redisClient.on('connection', () => { 
  console.info('Redis connected!');
}

Although I'm using the Windows, I downloaded Redis, performed a ping test, and confirmed that the server is running.

Share Improve this question asked Dec 2, 2021 at 9:31 Minwoo KimMinwoo Kim 5101 gold badge6 silver badges22 bronze badges 6
  • 1 Before redisClient.set(req.body.id, refreshToken); you have to use redisClient.connect(); – Mani Commented Dec 2, 2021 at 9:37
  • 1 @MinwooKim did you manage to find the solution? I also encounter this with NextJS. – Julio de Leon Commented Dec 8, 2021 at 5:38
  • 2 @MinwooKim uninstall your redis (npm uninstall redis), reinstall it using the version 3.0.2 (npm install [email protected]). Also use this installer github./microsoftarchive/redis/releases/tag/win-3.2.100 – Julio de Leon Commented Dec 8, 2021 at 6:41
  • 1 I ran into the same issue and used redis 3.02 (as you suggested) instead of redis 4.0 - and that fixed the error. Thanks @MinwooKim – tonethar Commented Dec 12, 2021 at 7:47
  • 1 @JuliodeLeon Sorry for the late reply. I solved the problem by keeping the existing redis package and performing initialization work through the connect() function. – Minwoo Kim Commented Dec 12, 2021 at 9:56
 |  Show 1 more ment

3 Answers 3

Reset to default 3

As for now I am able to solve partially to get data, but for set data still not done for redis v4. #redis #v4 # redisv4

app.get('/data',(req,res) => {
     // check in redis first
    //console.log(">>>>url",url)
    (async () => {
        const userInput = (req.query.country).trim()
        const url = `https://en.wikipedia/w/api.php?action=parse&format=json&section=0&page=${userInput}`
   
        const client = createClient({
            host:'localhost',
        port:6379});
      
        client.on('error', (err) => console.log('Redis Client Error', err));
      
        await client.connect();

        const response = await  client.get(`${userInput}`)
        if(response){
            const output = JSON.parse(response);
            res.send(output)
        }
      })();

})

According to the documentation, the client needs to be explicitly connected by way of the connect() function in order for the mands to be sent to the target Redis node(s):

await Redis.connect();

I implement connect to redis v6.2 this way in index.js start file.

const redis = require('redis');

const redisCache = createClient({
  url: redis://localhost:6379    
});
redisClient.on('connect', () => console.log('Connected to Redis!'));
redisClient.on('error', (err) => console.log('Redis Client Error', err));
redisClient.connect();

module.exports = redisClient;

本文标签: javascriptUnhandledPromiseRejectionWarning Error The client is closed in NodeJS and RedisStack Overflow