[英]Failed to load resource: the server responded with a status of 500 (Internal Server Error), Error: Request failed with status code 500
[英]Failed to load resource: the server responded with a status of 500 (Internal Server Error) in react
嘗試使用表單發布請求,但服務器響應 500 錯誤。 handlesubmit function 看起來像這樣,它不工作總是顯示帶有 500 代碼的內部服務器錯誤。
async function handleSubmit(e){
e.preventDefault();
SetBtnText("Sending...");
const response = await fetch("http://localhost/form/contact",
{
mode: 'no-cors',
method :"POST",
headers: {
"Content-Type": "application/json"
},
FormData
})
.then(resp => resp.json())
.then(data => console.log(data));
SetBtnText("Send");
let result = await response.json();
SetFormData(InitialFormData);
if (result.code === 200){
setStatus({ success: true, message: 'Message sent successfully' });
} else{
setStatus({ success: false, message: 'Something went wrong, please try again later.' });
}
}
Server.js 看起來像這樣..
const express = require('express')
const cors = require("cors");
const nodemailer = require("nodemailer");
const router = express.Router();
const dotenv = require('dotenv')
dotenv.config({path:"./.env"})
const app = express();
app.use('/form', router);
app.use(cors());
app.use(express.json());
app.listen(80 , ()=>{console.log("Server Running at Port:80")})
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
})
router.post('/contact',(req, res)=>{
const Name = req.body.FirstName + req.body.LastName;
const Email = req.body.Email;
const Message = req.body.Message;
const Phone = req.body.Phone;
const MailOptions = {
from : Email,
to :process.env.EMAIL,
subject: "Contact Form Submission - Portfolio",
html : `<p>Name: ${Name}</p>
<p>Email: ${Email}</p>
<p>Phone: ${Phone}</p>
<p>Message: ${Message}</p>`,
}
console.log(MailOptions)
transporter.sendMail(MailOptions, function(error){
if (error) {
res.json(error)
} else {
res.json({code:200 , msg : "Sent Successfully"})
}
});
});
我應該怎么做才能完成這項工作。 請建議我如何刪除此內部服務器錯誤
從您的代碼中,我可以看到您在反應端缺少服務器端口,它應該是http://localhost:80/form/contact
NOT http://localhost/form/contact
也在您已經使用 ZB439A4514C277CE6FCCC8F28 的服務器上需要在客戶端上設置no-cors
代碼將用於一點提示 使用Postman在將其集成到客戶端之前始終測試您的 API,這樣您可以確定問題不是來自服務器,如果它是修復它在客戶端嘗試之前
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.