错误:返回jwt.verify时,发送头后无法设置头

时间:2019-12-30 03:35:27

标签: javascript node.js express jwt

我想根据控制器上的功能进行身份验证,因此我使isAuthorized的功能如下:

const isAuthorized = (req) => {
  const token = req.cookies['jwt'];
  const sign = process.env.JWT_SECRET_KEY;

  return jwt.verify(token, sign, function(err, decoded) {
    console.log(decoded);
    if (err || !decoded) {
      console.log('invalid token');
      return false;
    } else if (decoded && (!decoded.access || decoded.access == 'unauthenticated')) {
      console.log('unauthenticated token');
      return false;
    } else if (decoded && decoded.access == 'authenticated') {
      console.log('valid token');
      return true;
    } else {
      console.log('something suspicious');
      return false;
    }
  });
};

用法:

const viewLogin = (req, res, next) => {
  if (isAuthorized(req)) {
    res.send('Already Logged In');
  }
  res.render('login');
};

它完全可以满足我的要求,但是在终端上出现错误。

GET /auth/login 200 8.810 ms - 17
Error: Can't set headers after they are sent.
    at SendStream.headersAlreadySent (/Users/james/Documents/Workspace/Centell/Project/weaver/node_modules/send/index.js:390:13)
    at SendStream.send (/Users/james/Documents/Workspace/Centell/Project/weaver/node_modules/send/index.js:618:10)
    at onstat (/Users/james/Documents/Workspace/Centell/Project/weaver/node_modules/send/index.js:730:10)
    at FSReqCallback.oncomplete (fs.js:159:5)

我试图:

  • 从外部(viewLogin)定义令牌,并将其作为参数(isAuthrized(token))发送。
  • 使用异步/等待模式。 (await usAuthrized(req)
  • isAuthorized中分隔结果变量。
const isAuthorized = req => {
  const token = req.cookies['jwt'];
  const sign = process.env.JWT_SECRET_KEY;
  let result;

  return jwt.verify(token, sign, function(err, decoded) {
    console.log(decoded);
    if (err || !decoded) {
      console.log('invalid token');
      result = false;
    } else if (decoded && (!decoded.access || decoded.access == 'unauthenticated')) {
      console.log('unauthenticated token');
      result = false;
    } else if (decoded && decoded.access == 'authenticated') {
      console.log('valid token');
      result = true;
    } else {
      console.log('something suspicious');
      result = false;
    }
  });

  return result;
};


但是这些不起作用。

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

更改代码如下:

const viewLogin = (req, res, next) => {
  if (isAuthorized(req)) {
    res.send('Already Logged In');
  } else {
    res.render('login');
  }
};

OR

const viewLogin = (req, res, next) => {
  if (isAuthorized(req)) {
    return res.send('Already Logged In');
  }
  res.render('login');
};

答案 1 :(得分:1)

解释为什么原件不起作用。由于已经使用res.send发送了响应,因此您将无法再使用res.render。为了防止执行res.render,您将需要返回res.send或使用if / else语句,如其他答案所示。