Express 应用程序出现错误“发送到客户端后无法设置标头”

编程入门 行业动态 更新时间:2024-10-03 14:30:00

Express 应用程序出现错误“<a href=https://www.elefans.com/category/jswz/34/1771275.html style=发送到客户端后无法设置标头”"/>

Express 应用程序出现错误“发送到客户端后无法设置标头”

我确实有意返回(因此 userExists 变量为 True)。 我多次遇到这个错误,但我不明白它是如何生成的

但是在 catch 块上,终端指针指向 return res.status(500).json({ 行。但我确信这是因为我在表单中使用了现有电子邮件

商店_用户代码:

const STORE_USER = async (req, res) => {
  try {
  
    const {
      name,
      surname,
      email,
      password,
      phone,
      country,
      city,
      address,
      zip,
      dob,
      gender,
    } = req.body;

    await prisma.$transaction(async (tx) => {
      const userExists = await tx.user.findFirst({
        where: {
          email,
        },
      });

      if (userExists) {  // userExists is True, so I guess it returned this
        return res.status(409).json({
          success: false,
          message: "User already exist",
          code: "B00001",
        });
      }

      const password_hashed = await bcrypt.hash(password, 10);

      const user = await tx.user.create({
        data: {
          name,
          surname,
          email,
          password: password_hashed,
          gender,
          phone,         
          address,
          zip,
        },
      });

       const token = crypto.randomBytes(30).toString("hex");

      await tx.verify_Account.create({
        data: {
          Users: {
            connect: {
              id: user.id,
            },
          },
          token,
        },
      });

      const romeTimezone = "Europe/Rome";
      const currentDateTimeInRome = utcToZonedTime(new Date(), romeTimezone);

      // Add 2 hours to the current date and time in Rome
      const newDateTimeInRome = addHours(currentDateTimeInRome, 2);

      // Format the date in the desired format (dd/mm/yyyy hh:mm)
      const dateFormat = "dd/MM/yyyy HH:mm";
      const token_expiration_datetime = format(newDateTimeInRome, dateFormat, {
        timeZone: romeTimezone,
      });

      sendEmailRegistration(   //Is an async Function that in //success return res.status with json
        email,
        name,
        surname,
        token,
        token_expiration_datetime
      );
    });

    return res.status(200).json({
      success: true,
    });
  } catch (error) {
    console.log(error);
    return res.status(500).json({
      success: false,
      code: "A00010",
    });
  }
};

发送邮件注册码:

const sendEmailRegistration = async (
  email,
  name,
  surname,
  token,
  token_expiration_datetime
) => {
  // Create a transporter object using Gmail SMTP transport
  const transporter = nodemailer.createTransport({
    service: process.env.EMAIL_SERVICE,
    auth: {
      user: process.env.EMAIL_USERNAME,
      pass: process.env.EMAIL_PASSWORD,
    },
  });

  const currentYear = new Date().getFullYear();

  const URL = `${process.env.FRONTEND_URL}/verify_account?token=${token}`;

  subject = "Test- Test";
  html = `
  <div>
Test
  </div>
`;

  // Define the email options
  const mailOptions = {
    from: process.env.EMAIL_USERNAME,
    to: process.env.IS_PRODUCTION ? email : "[email protected]",
    subject: subject,
    html: html,
  };

  // Send the email
  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      console.log("Error occurred:", error.message);
      return res.status(500).json({ message: "Error occurred" });
    } else {
      console.log("Email sent successfully!", info.response);
      return res.status(200).json({ message: "Email sent successfully!" });
    }
  });
};

有人可以解释一下这个错误是如何发生的吗?

回答如下:

据我了解,当多次向客户端发送响应时会发生这种情况。例如,res.status 和 res.send。

更多推荐

Express 应用程序出现错误“发送到客户端后无法设置标头”

本文发布于:2024-05-31 06:00:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771348.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   应用程序   出现错误   客户端   Express

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!