Axios 错误 422 是指请求无法被处理的实体,通常是由于请求的数据格式不正确导致的。根据你提供的信息,你正在使用 FastAPI 后端和 React 前端进行电子邮件验证代码的发送。
以下是一个可能的解决方案,包含代码示例:
React 前端示例代码:
import axios from 'axios';
const sendVerificationCode = async (email) => {
try {
const response = await axios.post('/api/send-verification-code', {
email: email
});
console.log(response.data);
} catch (error) {
console.error(error);
}
}
FastAPI 后端示例代码:
from fastapi import FastAPI
from fastapi import HTTPException
from pydantic import BaseModel
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
app = FastAPI()
# 邮件配置
conf = ConnectionConfig(
MAIL_USERNAME = "your-email@gmail.com",
MAIL_PASSWORD = "your-email-password",
MAIL_FROM = "your-email@gmail.com",
MAIL_PORT = 587,
MAIL_SERVER = "smtp.gmail.com",
MAIL_TLS = True,
MAIL_SSL = False,
USE_CREDENTIALS = True
)
# 请求模型
class EmailRequest(BaseModel):
email: str
# 发送邮件路由
@app.post("/api/send-verification-code")
async def send_verification_code(request: EmailRequest):
try:
# 根据 request.email 发送电子邮件验证代码
message = MessageSchema(
subject="Verification Code",
recipients=[request.email],
body="Your verification code is: 123456"
)
fm = FastMail(conf)
await fm.send_message(message)
return {"message": "Verification code sent successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to send verification code: {str(e)}")
上述示例代码假设你正在使用 Gmail SMTP 服务器发送电子邮件。你需要将 MAIL_USERNAME 和 MAIL_PASSWORD 替换为你自己的 Gmail 邮箱和密码。
请注意,在上述示例中,我们使用了第三方库 fastapi-mail 来简化发送邮件的过程。你可以使用其他发送电子邮件的库,根据你的实际需求进行调整。
希望这能帮助到你解决问题!