redis的get和set方法在node应用程序中不起作用

31moq8wy  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(88)

Redis连接正确,但之后,它不显示代码的输出。Redis客户端也正确地将name设置为key,但在此之后,它不会显示任何重播错误作为输出,同样的事情发生在get方法上。

const express = require('express');
const redis = require("redis");
const client = redis.createClient();
client.connect();
client.on("connect", (err)=>{
    if(err) throw err; 
    else console.log("Redis Connected!");
});
const app = express();
app.get('/',(req,res)=>{
    let name = req.query['name'];
    client.set("name", name, (err, replay)=>{
        if(err) throw err;
        else console.log(replay); //ok
    });
    client.get("name", (err, name)=>{
        if(err) throw err;
        else {
            console.log(`name: ${name}`); 
            res.send(`hello ${name}`);
        }
    });
});

app.listen('3000',()=>{
    console.log("server at 3000.!");
});

字符串
输出:https://i.stack.imgur.com/p2C2V.jpg

lokaqttq

lokaqttq1#

创建client.js文件。client.js内部

const { createClient } = require('redis');
const dotenv = require('dotenv');
dotenv.config({ path: './.env' });

const client = createClient({
    socket: {
        host: process.env.REDIS_HOST,
        port: parseInt(process.env.REDIS_PORT),
    },
    password: process.env.REDIS_PW,
});

client.on('error', (err) => console.log(err));
client.connect();

module.exports = client;

字符串
您可以在Redis云控制台中获取REDIS_HOST、PORT、PW。确保将这些密钥存储到.env文件中,现在执行以下操作:

const express = require('express');
const client = require('./client');
const app = express();
app.get('/',(req,res)=>{
    let name = req.query['name'];
    client.SET("name", name);
    client.get("name", (err, name)=>{
        if(err) throw err;
        else {
            console.log(`name: ${name}`); 
            res.send(`hello ${name}`);
        }
    });
});

app.listen('3000',()=>{
    console.log("server at 3000.!");
});

相关问题