发送给客户端后无法设置 headers - 正在发送 SES 电子邮件

Cannot set headers after they are sent to the client - Sending SES email

我正在尝试构建一个 pw 恢复解决方案,并在 app.post 方法中添加了 SES 代码,但我一直收到 Cannot set headers after they are sent to the client。正在触发错误。

ses.sendRawEmail(params, function(err, data) {
         if(err) {
      res.send(err);
         }

我在 User.findOne 之前添加了参数代码,认为可行,但我猜它在到达 Api 端点之前正在谈论 headers。在那种情况下,除非我弄错了,否则这不会使这成为可能。如何让 AWS SES 代码在 app.post?

中正常运行
   app.post("/api/users/passwordreset", function(req, res) {
console.log(req.body.email);
let emailValue = req.body.email;

  if (req.body.email !== undefined) {

    // TODO: Using email, find user from your database.


    var ses_mail = "From: 'Auction Site' <" + emailValue+ ">\n";
    ses_mail = ses_mail + "To: " +emailValue + "\n";
    ses_mail = ses_mail + "Subject: Password Reset Request\n";
    ses_mail = ses_mail + "MIME-Version: 1.0\n";
    ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";
    ses_mail = ses_mail + "--NextPart\n";
    ses_mail = ses_mail + "Content-Type: text/html; charset=us-ascii\n\n";
    ses_mail = ses_mail + "Click here to reset password." + "\n\n" + 'http://localhost:3000/resetpassword';


    var params = {
      RawMessage: { Data: new Buffer.from(ses_mail) },
      Destinations: [emailValue ],
      Source: "'AWS Tutorial Series' <" + emailValue + ">'"

  };



    User.findOne({ email: req.body.email })
    .then(user => {
      if(user){
        console.log("fetchedUser");
        console.log(user);
        var payload = {
          id: user.id, // User ID from database
          email: user.email
        };

         var secret = user.password + "-" + user.creationDate;
         var token = jwt.sign(payload, secret);
         console.log("payload");
         console.log(token);

         ses.sendRawEmail(params, function(err, data) {
          if(err) {

              res.send(err);
          }
          else {
              res.send(data);
          }
      });

        res.send(
          '<a href="/resetpassword/' +
            payload.id +
            "/" +
            token +
            '">Reset password</a>'
        );

    }
      if (!user) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }


    });

    // TODO: Make this a one-time-use token by using the user's
    // current password hash from the database, and combine it
    // with the user's created date to make a very unique secret key!
    // For example:
    // var secret = user.password + ‘-' + user.created.getTime();

    // TODO: Send email containing link to reset password.
    // In our case, will just return a link to click.
  } else {
    res.send("Email address is missing.");
  }
});

问题是您多次使用 res.send。一切都承诺,它会很好地工作