html代码的形式。它的简单名称,第二名,电话,邮件,消息(textarea teg*)与提交按钮。
<form method="post" class="register-form" id="contact-form">
<div class="row">
<div class="col-sm-6">
<label for="firstName" class="mb-1">First name <span
class="text-danger">*</span></label>
<div class="input-group mb-3">
<input name="first-name" type="text" class="form-control" id="firstName" required placeholder="First name" aria-label="First name">
</div>
</div>
<div class="col-sm-6 ">
<label for="lastName" class="mb-1">Last name</label>
<div class="input-group mb-3">
<input name="last-name" type="text" class="form-control" id="lastName" placeholder="Last name" aria-label="Last name">
</div>
</div>
<div class="col-sm-6">
<label for="phone" class="mb-1">Phone <span class="text-danger">*</span></label>
<div class="input-group mb-3">
<input name="phone" type="text" class="form-control" id="phone" required placeholder="Phone" aria-label="Phone">
</div>
</div>
<div class="col-sm-6">
<label for="email" class="mb-1">Email<span class="text-danger">*</span></label>
<div class="input-group mb-3">
<input name="email" type="email" class="form-control" id="email" required placeholder="Email" aria-label="Email">
</div>
</div>
<div class="col-12">
<label for="yourMessage" class="mb-1">Message <span class="text-danger">*</span></label>
<div class="input-group mb-3">
<textarea class="form-control" id="yourMessage" required placeholder="How can we help you?" style="height: 120px"></textarea>
</div>
</div>
</div>
<button id="submit" type="submit" class="btn btn-primary mt-4">Get in Touch</button>
</form>
js代码从表单中收集数据。
我也尝试让5 const为我所有的输入,但它仍然没有发送到服务器。
<script type="text/javascript">
const form = document.querySelector('#contact-form');
const message = document.getElementById('yourMessage')
form.addEventListener('submit', (event) => {
event.preventDefault();
//collecting <form> data
const formData = new FormData(form);
formData.append('message',message.value)
fetch('/contact', {
method: 'POST',
body: formData
})
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.error(error);
})
});
</script>
基于gulpfile.js的服务器端代码
我不明白哪里出错了。
我只是猜测问题是在身体解析器,但idk。
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");
const express = require("express");
const app = express();
app.use(express.static("dist"));
app.use(bodyParser.json());
//nodemailer
app.use(express.urlencoded({ extended: false }));
app.post("/contact", (req, res) => {
const formData = req.body.name;
res.json({ message: "Form data received!", formData: formData });
console.log(formData); //{undefined} but i need data like {name: ... , mail: ...}
我解决了。我所需要做的就是:<form method="post" action="/contact">
对于服务器端代码:
const urlencodedParser = express.urlencoded({ extended: false });
app.post("/contact", urlencodedParser, (req, res) => {
if (!req.body) return res.sendStatus(400)})