I am using following code using react js, Nodemailer.my server.js file is working fine and sending email but whenever I my ContactForm it is showing message "cannot post". does the app.listen port number is making problem ?
whenever I send email using node server.js its working fine.
.please advice
server.js file
const express = require("express");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");
const app = express();
app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(3005, () => console.log("Server Running"));
const contactEmail = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '***@gmail.com',
pass: '*****'
},
});
contactEmail.verify((error) => {
if (error) {
console.log(error);
} else {
console.log("Ready to Send");
}
});
router.post("contact", (req, res) => {
const name = req.body.name;
const email = req.body.email;
const message = req.body.message;
const mail = {
from: name,
to: "*****@yahoo.com",
subject: "Contact Form Message",
html: `<p>Name: ${name}</p><p>Email: ${email}</p><p>Message: ${message}</p>`,
};
contactEmail.sendMail(mail, (error) => {
if (error) {
res.json({ status: "ERROR" });
} else {
res.json({ status: "Message Sent" });
}
});
});
---------
ContactForm.js
import React, { useState } from "react";
const ContactForm = () => {
const [status, setStatus] = useState("Submit");
const handleSubmit = async (e) => {
e.preventDefault();
setStatus("Sending...");
const { name, email, message } = e.target.elements;
let details = {
name: name.value,
email: email.value,
message: message.value,
};
let response = await fetch("http://localhost:3005/contact", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
},
body: JSON.stringify(details),
});
setStatus("Submit");
let result = await response.json();
alert(result.status);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input type="text" id="name" required />
</div>
<div>
<label htmlFor="email">Email:</label>
<input type="email" id="email" required />
</div>
<div>
<label htmlFor="message">Message:</label>
<textarea id="message" required />
</div>
<button type="submit">{status}</button>
</form>
);
};
export default ContactForm;
question from:
https://stackoverflow.com/questions/65866184/i-am-using-following-code-my-server-js-file-is-working-fine-but-contactform-is-s 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…