My fetch 适用于帖子但不适用于 js 中的 xhr

问题描述 投票:0回答:1

我创建了一个报告表格,并在编写报告后使用 nodemailer 库发送电子邮件。我曾经在 html 中使用一个看起来像这样的标签:

<form action="/sendReport" method="post" >
但由于我不会深入的原因,我更喜欢跳过在 js 中发送。所以我试着做一个 fetch 但显然它不起作用

这里是 html :

        <div>
          <label for="email">E-mail address</label>
          <input type="text" id="emailReport" name="email" placeholder="Enter your email address" required>
        </div>

        <div>
          <label for="subject">Subject</label>
          <input type="text" id="subjectReport" name="subject" placeholder="Enter the subject of the bug" required>
        </div>

        <div>
          <label for="description">Description of the bug</label>
          <textarea rows="8" cols="30" id="descriptionReport" name="description" placeholder="Describe the bug you encountered" required></textarea>
        </div>

        <div>
          <button onclick="sendReport()">Send the report</button>
        </div>

这里是 js :

function sendReport() {
  // Collect report information from the DOM
  const email = document.getElementById('emailReport').value;
  const subject = document.getElementById('subjectReport').value;
  const description = document.getElementById('descriptionReport').value;
  console.log(email, subject, description);

  // Send the report information via an HTTP POST request
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/sendReport', true);
  xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
  xhr.onload = function() {
    if (xhr.status === 200) {
      console.log('Report sent successfully');
//do something...
    } else {
      console.error('Error when sending the report');
//do something else...
    }
  };
  xhr.onerror = function() {
    console.error('Error when sending the report');
  };
  xhr.send(JSON.stringify({email, subject, description}));
}

这是我的收获:


const transporter = nodemailer.createTransport({
//config stuff...
});

app.post('/sendReport', (req, res) => {
  const email = req.body.email;
  const subject = req.body.subject;
  const description = req.body.description;

console.log(email, subject, description); //here i have undefined
  const mailOptions = {
    from: 'my@email',
    to: 'my@email',
    subject: subject,
    text: description
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log(error);
      res.status(500).send('Error');
    } else {
      console.log(email, subject, description); //here i have undefined too
      console.log('E-mail send: ' + info.response);
      
    }
  });
});

javascript node.js fetch-api nodemailer
1个回答
0
投票

在您的服务器中添加

app.use(express.json())
;

© www.soinside.com 2019 - 2024. All rights reserved.