首页 > 解决方案 > 重定向到用户

问题描述

这是一个开放的代码,因为通过电子邮件结束给用户的电子邮件,当他们打开链接时,它会引导到端点处的用户。

在函数结束时,我想将用户重定向到新页面,但重定向不起作用,为什么它不起作用?

async getToken(req, res) {
    // const { token } = req.params;
    let { access_token } = req.query;
    access_token = access_token.replace(/\s/g, '');


    let decoded;
    try {
      decoded = jwt.verify(access_token, process.env.JWT_ACCOUNT_ACTIVATION);
      const email_consulted = decoded.email; // you are returning a success response but you havent finished the process yet. Usually the success is sent on the end of the process
      let select = await pool.query(
        `SELECT User_email FROM user WHERE User_email='${email_consulted}'`
      );

   

    //   console.log(select);

      if (select.length > 0) {
        return res.json({
          success: false,
          code: 400,
          message: "Email ya existe"
        });
      }

      const result = await pool.query(
        `INSERT INTO user (User_email) VALUES ('${email_consulted}')`
      );
      let selectid = await pool.query(
        `SELECT ID_user FROM user WHERE User_email='${email_consulted}'`
      );

      const id = selectid[0].ID_user

      const token = jwt.sign(
        { id }, 
         process.env.JWT_ACCOUNT_ACTIVATION,
        {expiresIn: '30d' }
    )
      res.cookie("_$",token);
      res.json({
        sucess: true,
        code: 201,
        message: "Usuario añadido exitosamente",
        token
      });
 
      return window.location.replace("http://seth.com/dashboard.html?ftime=0");
      // if (select != "") {
      //     const result = await pool.query(`INSERT INTO user (User_email) VALUES (${email_consulted})`);
      // }
    } catch (err) {
      return res.json({ message: "Internal server error" });
    }
  }

标签: javascriptnode.jsjsonnpm

解决方案


您正在尝试在服务器上重定向,而不是在客户端上。 window未在服务器上定义,因此这将导致错误。使用该res对象返回您的响应,就像您已经在其他地方所做的那样。在这种情况下,响应是重定向:

res.redirect('http://seth.com/dashboard.html?ftime=0');

旁注:您不需要,只需适当地return res...调用函数即可。res对象本身(以及随后的res框架)负责响应客户端,而不是您。


推荐阅读