首页 文章

Headers 已经发送 - Koa和bcrypt

提问于
浏览
1

我在创建用户时使用了bcrypt来哈希密码 . 登录时,我想将哈希值与字符串密码进行比较 . 但是,当我使用邮递员登录时,我收到404错误"headers have already been sent" . 我查看了koa git论坛using crypto with koa 2,并且接受的答案建议将函数包装在异步等待中,这就是我为什么节点不断向我发送'headers have already been sent'错误 .

var User = db.get('users');
var Review = db.get('reviews');

//this create user function works as intended...

module.exports.create = async (ctx, next) => {
  if ('POST' != ctx.method) return await next();

  let user = ctx.request.body;

  console.log('CREATE USER params:');
  console.log(user);

  console.log(user.username);
  let users = await User.find({username:user.username});
  console.log(users); //why is this a function???
  if (users.length > 0) {
    ctx.status = 400;
    ctx.body = {
      errors:[
        'Username already exists.'
      ]
    };
  } else {
    const hash = await bcrypt.hash(user.password, 10);
    await User.insert({username:user.username, password:hash});
    console.log('Creating user…');
    console.log(user);
    ctx.body = filterProps(user, ['username']);
    ctx.status = 201;
    }
  };

module.exports.signIn = async (ctx, next) => {

  const encoded = ctx.request.headers.authorization.split(' ')[1];
  const decoded = base64url.decode(encoded);
  const [username, password] = decoded.split(':');
  const user = await User.findOne({username:username});
 
  //problematic code here...

  await bcrypt.compare(password, user.password, function (err, res) {
    if (res) {
      ctx.status = 200;
      ctx.body = 'success';
    } else {
      ctx.status = 401;
      ctx.body = {
        errors:['password incorrect for this username']
      }
    }
  });
}

1 回答

  • 1

    所以问题在于我如何使用bcrypt比较 . 我将结果存储在变量中,而不是使用回调,它可以工作 . 为什么,我不知道......

    module.exports.signIn = async (ctx, next) => {
      const encoded = ctx.request.headers.authorization.split(' ')[1];
      const decoded = base64url.decode(encoded);
      const [username, password] = decoded.split(':');
      const user = await User.findOne({username:username});
      
      const correct = await bcrypt.compare(password, user.password)
      if (correct) {
        ctx.status = 200;
        ctx.body = 'success';
      }
      else {
        ctx.status = 401;
        ctx.body = {
          errors:['wrong credentials']
        }
      }
    };
    

相关问题