Home > Software design >  trying to use express and redis to make a login web page
trying to use express and redis to make a login web page

Time:10-03

im trying to make a simple login to a web project i have to do for univercity. the probelm is pretty simple, im trying to use redis to be the database for the users and passwords. the problem is that i cant extract the values out of the response i get from redis, i got a docker running the redis image and every thing connect, in the example below im trying to make a simple boolean change from true to false according to the data inside the key (im using "a" as the key) but no matter what i do the value doesn't seem to change, it is note worthy that im very new to this and to js in particular, i read in the redis api that all of the funtions are asyncs i tried changing the code but it didnt help.

 app.get('/enter', (req, res) => {
  var username =req.query.user;
  var password = req.query.pass;
  ans = false
  redis.get(username,function(err, reply) {
    if(reply != null ) ans = true;
  })
  console.log(ans);
})

i just trying to verify that the key has a value, i tried the make a variable before and after the request but it not adjusting thanks for your time

CodePudding user response:

I see you dont understand the very very basics of callbacks and asynchronouse behaviour of javascript.

Well you can code like this:

app.get('/enter', async (req, res) => {
  var username =req.query.user;
  var password = req.query.pass;
  ans = false
  let reply = await getUsername(username)
  console.log(reply)
  console.log(ans);
})

function getUsername(username) {
   return new Promise((res, rej) => {
      redis.get(username, function(err, reply) {
         if(err) rej(err)
         res(reply)
      })
   })
}

You can just promisfy your redis code with new Promise and then you can use async / await style on it

Otherwise you need to write your code in the callback witch leads to an callback hell if you have more code

  • Related