我已经在authateUser.js中创建了authenticateUser个中间件,

async function authenticateUser(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return res.status(401).json({ message: 'Unauthorized access!' });

  }

  try {
    const accessToken = await authHeader.split(' ')[1];
    // Check if the user exists and has the same access token
// Verify the JWT access token and extract the payload
const payload = jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET);
   // const role = payload.role;
   const {email,uid, role} = payload;

   
    const user = await UserClient.findOne({ email });
    if (!user || user.accessToken !== accessToken) {
      return res.status(401).json({ message: 'Unauthorized access!' });
    }
 

    // expose the user role , client Id from the payload object for further processing
    req.role = role;
    req.email = email;
    req.uid = uid;

    // Call the next middleware to continue with the request processing
    next();
  } catch (error) {
    return res.status(401).json({ message: 'Unauthorized access!' });
  }
}

在这里,当我需要在另一个路由中使用EMAIL值时,比方说router.get("/user",authenticateUser,async(req,res)=>{}),我可以使用const email= req.email; console.log(email)在users.js模块中使用EMAIL值.一百零二

我需要使用email值的函数如下(在sites.js文件中);

    async function addSitesToUser() {
      try {
<-------Need to use email value here-------->
        const userData = await UserClient.findOne({email});
    
        if(!userData.siteList || userData.siteList.length === 0){
          const updatedSites = await UserClient.findOneAndUpdate(
            { email },
            { $push: { siteList: { $each: sites } } },
            { upsert: true,new: true }
          );
        } else{
          const existingSiteIds = userData.siteList.map(site => site.siteId);
          // console.log("**exist: "+existingSiteIds)
          const newSites = sites.filter(site => !existingSiteIds.includes(site.siteId));
          // console.log("**newsit: "+newSites)
          userData.siteList.push(...newSites);
          await userData.save();
        }
      } catch (error) {
        console.error('Error adding sites');
      }
    }

我从index.js await addSitesToUser();中调用了上面的函数

推荐答案

您可以将邮箱作为输入传递给函数

router.get("/user",authenticateUser,async(req,res)=>{
    await addSitesToUser(req.email)
})

但有一种更好的方法来解决这一问题. 在对请求进行身份验证时,您已经获取了用户一次. 只需在请求中设置整个User对象,就不必在该特定请求的生命周期中的任何位置获取它. 因此,在中间件中,只需执行

req.user = user

然后将req对象传递给函数,这样您就可以从任何函数访问用户

router.get("/user", authenticateUser, async (req, res) => {
  await addSitesToUser(req);
  // function body
});

和内部的addSitesToUser函数

async function addSitesToUser(req) {
      try {
        const userData = req.user;

        // do whatever you want to do
      } catch (error) {
        console.error('Error adding sites');
      }
    }

Javascript相关问答推荐

调用SEARCH函数后,程序不会结束

Next.js Next/Image图像隐含性有任何类型-如何修复?

如何最好地从TypScript中的enum获取值

通过使用100%间隔时间来代表我们还剩多少时间来倒计时

没有输出到带有chrome.Devtools扩展的控制台

jQuery提交按钮重新加载页面,即使在WordPress中使用preventDefault()

在观察框架中搜索CSV数据

在服务器上放置了Create Reaction App Build之后的空白页面

虚拟滚动实现使向下滚动可滚动到末尾

JSDoc创建并从另一个文件导入类型

我的角模板订阅后不刷新'

Chart.js-显示值应该在其中的引用区域

我可以使用使用node.js创建的本地主机来存储我网站上提交的所有数据吗?没有SQL或任何数据库.只有HTML语言

如何在Bootstrap中减少网格系统中单个div的宽度

自定义图表工具提示以仅显示Y值

Phaserjs-创建带有层纹理的精灵层以自定义外观

如何使用<;Link>;执行与JS Reaction中的";window.Location=/GameOverDied;";类似的操作?

JavaScript:如果字符串不是A或B,则

为什么我看到的是回复,而不是我的文档?

为什么在运行于<;img>;事件处理程序中的JavaScript中x和y是不可变的?