import React, { useState } from 'react';
import axios from 'axios';
function Form() {
const [formData, setFormData] = useState({
name: '',
email: ''
});
const handleChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async e => {
e.preventDefault();
try {
await axios.post('http://localhost:5000/submit', formData);
alert('Form submitted successfully!');
} catch (error) {
console.error(error);
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" value={formData.name} onChange={handleChange} placeholder="Name" required />
<input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="Email" required />
<button type="submit">Submit</button>
</form>
);
}
export default Form;
const express = require('express');
const axios = require('axios');
const nodemailer = require('nodemailer');
const app = express();
app.use(express.json());
app.post('/submit', async (req, res) => {
const { name, email } = req.body;
// 发送邮件
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your-email@gmail.com',
pass: 'your-password'
}
});
const mailOptions = {
from: 'your-email@gmail.com',
to: 'recipient@example.com',
subject: 'New Form Submission',
text: `Name: ${name}, Email: ${email}`
};
await transporter.sendMail(mailOptions);
res.status(200).send('Form submitted successfully!');
});
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
原因: 可能是由于网络问题、服务器未启动或请求URL错误。
解决方法:
原因: 可能是由于邮件服务配置错误、认证失败或网络问题。
解决方法:
原因: 可能是由于请求URL错误、请求方法不正确或服务器未启动。
解决方法:
希望这些信息对你有所帮助!如果有更多问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云