javascript 如何将用户数据发送到node js中的下一个函数?

sqxo8psd  于 2023-05-12  发布在  Java
关注(0)|答案(2)|浏览(60)

我想实现的功能,检查是否有一个令牌,验证令牌,并赠款访问受保护的路由,但我不知道如何发送用户数据到下一个功能。
authController.js文件-

exports.protect = async (req, res, next) => {
  //1) Getting token and check if it's there
  let token;
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    token = req.headers.authorization.split(" ")[1];
  } else if (req.cookies.jwt) {
    token = req.cookies.jwt;
  }

  if (!token) {
    res.status(401).json({
      status: "fail",
      message: "You are not logged in. Please login to get access",
    });
    next();
  }
  //2) Verificating the token

  //const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);
  
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  
  let currentUser;
  //3)Check if user still exists
  db.getConnection(async (err, connection) => {
    const sqlSearch = "SELECT * FROM users WHERE id = ?";
    const sqlQuery = mysql.format(sqlSearch, [decoded.id]);
    connection.query(sqlQuery, (err, result) => {
      connection.release();
      currentUser = result;
    });
  });
  if (!currentUser) {
    res.status(401).json({
      status: "fail",
      message: "The user belonging to this token does no longer exist",
    });
    next();
  }

  //GRANT ACCESS TO PROTECTED ROUTE
  req.user = currentUser;
  res.locals.user = currentUser;
  next();
};

courseRouter.js文件-

const express = require('express');
const coursesController = require('../controllers/coursesController');
const authController = require('../controllers/authController');
const router = express.Router();

router.get('/', coursesController.getAllCourses);
router.post('/:slug', authController.protect, coursesController.buyCourse);

module.exports = router;

连接到数据库后,我不知道如何将用户数据返回给buyCourse()函数。我这样做的方式是“currentUser”未定义。

yws3nbqq

yws3nbqq1#

我建议使用AsyncLocalStorage将登录用户存储在基于上下文的存储中,并授予对链中任何函数的访问权限。这将确保登录用户的上下文在同一执行上下文内的不同函数调用中得到维护。
您可以参考Node.js文档了解使用方法:https://nodejs.org/api/async_context.html
AsyncLocalStorage是一个单例示例,您可以在每个传入请求上使用它的run()方法来设置上下文并存储登录的用户信息。

afdcj2ne

afdcj2ne2#

您对response.locals.user的使用看起来相当标准。声明buyCourse以接受请求和响应对象,如下所示:

buyCourse(request, response) {
  // Use response.locals.user
}

但是您并没有等待数据库结果,所以在设置currentUser时,它仍然是null。试着这样写:

try {
  const connection = await db.getConnection();
  const sqlSearch = "SELECT * FROM users WHERE id = ?";
  const sqlQuery = mysql.format(sqlSearch, [decoded.id]);
  const result = await connection.query(sqlQuery);
  connection.release();
  currentUser = result;

  // Validation

  res.locals.user = currentUser;

} catch(e) {
  // Handle errors
}

相关问题