当我想通过React网站或 Postman 发送电子邮件时,出现了一些错误。在网站上显示无法POST /contact。
下面是index.js文件:
const express = require('express')
const app = express()
const nodemailer = require('nodemailer')
const cors = require('cors')
const bodyParser = require('body-parser')
const dotenv = require('dotenv')
const port = process.env.PORT || 5000
const EmailSender = require('./SendEmail.js')
app.use(cors());
app.use(bodyParser.json({limit: "25mb"}));
app.use(bodyParser.urlencoded({limit: "25mb", extended: true}));
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
app.get('/', (req, res) => {
res.send('Nothing important')
})
//send api
app.post('/send', async (req, res) => {
try {
const { user_email, messageSubject, message } = req.body
EmailSender({user_email, messageSubject, message})
res.json({msg: "Your message has been sent successfully"})
} catch (error) {
res.status(404).json({msg: "Error..."})
}
})
app.listen(port, () => {
console.log(`Server is now running at http://localhost:${port}`)
})
字符串
下面是SendEmail.js文件:
const nodemailer = require('nodemailer')
const dotenv = require("dotenv")
const Email = (options) => {
let transporter = nodemailer.createTransport({
service:'gmail', //maybe hotmail instead
auth: {
user: process.env.USER, //user or email
pass: process.env.PASSWORD//password
},
})
transporter.sendMail(options, (err, info) => {
if(err) {
console.log(err)
return err;
}
})
}
const EmailSender = ({user_email, messageSubject, message}) => {
const options = {
from: user_email,
to: process.env.USER,
subject: messageSubject,
message: message,
}
Email(options)
}
型
这是我的表格:
import React from 'react'
import axios from 'axios'
function ContactUs() {
const [user_email, setEmail] = React.useState("");
const [messageSubject, setSubject] = React.useState("");
const [message, setMessage] = React.useState("");
function sendEmail() {
if(user_email && messageSubject && message) {
axios
.post("http://localhost:5000/send", {
user_email: user_email,
subject: messageSubject,
message: message,
})
.then(() => alert("Email has been sent succesfuly"))
.catch(() => alert("Something went wrong..."))
return;
}
}
return (
<p className='title' id='Title' style={{display: show ? 'block' : 'none'}}>Contact Us</p>
<form method='post'>
<input type={'email'} id='emailInput' onChange={(e) => setEmail(e.target.value)} name='email' placeholder='email' required/>
<input type={'text'} id='subject' onChange={(e) => setSubject(e.target.value)} name='subject' placeholder='subject' required/>
<textarea type={'text'} id='message' onChange={(e) => setMessage(e.target.value)} name='message' placeholder='write a message...' required/>
<button className='submit' type='submit' onClick={() => sendEmail()}>Submit</button>
</form>
</div>
)
}
型
我试着改变一些变量。我也在互联网上搜索,但没有帮助。
我尝试执行error.reason
,但显示“undefined”。
1条答案
按热度按时间31moq8wy1#
问题是,我需要生成一个特殊的密码,因为gmail已经增强了安全性,以减轻未经授权的人入侵你的gmail的风险。你可以在你的帐户管理器中生成这个密码。