1

我正在尝试将 AJAX 用于我的联系表单,它将表单数据发送到服务器。然后应该通过输入字段向我发送用户信息。

我遇到的问题是,formData 似乎正常运行(出现在浏览器的网络中)但是当我的电子邮件通过时,我得到了未定义的值?

const submit = document.querySelector('.contact-btn');

submit.addEventListener('click', send);

function send(event){
    event.preventDefault();
    const url = "https://us-central1-selexin-website.cloudfunctions.net/app/sendemail";
    let form = document.querySelector('form');
    let formData = new FormData(form);
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        if(xhr.readyState === XMLHttpRequest.DONE){
            console.log(formData)
    // Make a pop up message in green below the textarea box to notify user email was sent.

    }   
}
    xhr.open('POST', url, true);
    xhr.send(formData);
};

以下是通过电子邮件发送给我的字段。如您所见,在电子邮件正文中,我将“运行测试”添加为字符串,并在电子邮件中返回完美。为什么 req.body 给我未定义的值?

const transport = nodemailer.createTransport(sendgridTransport({
    auth: {
        api_key: apiKey
    },
}));

app.use(express.urlencoded({extended: false}));
app.use(cors({ origin: true }));

app.post('/sendemail', (req, res) => {
  const {name, email, number, message} = req.body;
    return transport.sendMail({
    to: 'email receiving', 
    from: 'from this email',
    subject: 'New Contact Request',
    html: `
    <p>You have a new Contact Request</p>
    <h3>Contact Details</h3>
    <ul>
        <li>Name: 'Run test'</li>
        <li>Email: ${email}</li>
        <li>Number: ${number}</li>
        <li>Message: ${message}</li>
    </ul>
    `
    }).then(() => {
      if(res.sendStatus(200)){
        console.log('it logs');
      };
    })
 });

exports.app=functions.https.onRequest(app);
4

1 回答 1

1

您将请求正文发送为multipart/form-data,而不是application/x-www-form-urlencoded

如果您想处理前者,则需要在您的 express 应用程序中使用Multer 中间件之类的东西。

快速简便的解决方案是将您FormDataURLSearchParams

xhr.send(new URLSearchParams(formData))

这会将您的数据发布为由您已经在使用application/x-www-form-urlencoded的中间件处理的数据。express.urlencoded()


我还强烈建议将事件侦听器添加到表单的提交事件中,而不是单击按钮。这样,您可以捕获诸如“类型Enter提交”之类的内容

document.querySelector("form").addEventListener("submit", e => {
  e.preventDefault()
  const formData = new FormData(e.target)

  // ...and the rest of your "send" logic
})
于 2021-08-26T04:58:04.370 回答