如何修复ERR_SSL_PROTOCOL_ERROR?Go后端+React前端部署问题
问题描述
我已将React前端部署到GoDaddy服务器及对应域名https://cihanbatasul.com上,使用Go语言编写的后端被打包为容器,该后端仅提供一个用于发送邮件的API接口。前端调用接口时出现CORS相关错误,请求协助解决。
React前端组件代码
import React, { SetStateAction, useState } from "react"; import Input from "./Input"; import Button from "./Button"; import { motion, easeIn } from "framer-motion"; export interface email { senderEmail: string; senderName: string; message: string; } type responseProps = { response: React.Dispatch<SetStateAction<boolean | null>>; }; const Form = (props: responseProps) => { const [data, setData] = useState<email>({ senderEmail: "", senderName: "", message: "", }); const sendEmail = async () => { const url = "https://ip:8080/email/"; try { const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); if (response.ok) { props.response(true); } else { props.response(false); } } catch (error) { props.response(false); console.error(error); } }; return ( <motion.div initial={{ opacity: 0, x: -200 }} whileInView={{ opacity: 1, x: 0 }} transition={{ duration: 0.6, ease: easeIn }} viewport={{ once: true }} className="w-full m-auto flex flex-col gap-6 " > <div className="flex w-full gap-3 "> <Input onChange={setData} type="text" text="Name" /> <Input onChange={setData} type="email" text="Email" /> </div> <Input onChange={setData} type="text" text="Message" msg={true} /> <div className="w-full flex "> <Button onClick={sendEmail} /> </div> </motion.div> ); }; export default Form;
Go后端代码
package main import ( "encoding/json" "fmt" "log" "net/http" "net/smtp" "github.com/rs/cors" ) type EmailRequest struct { SenderEmail string `json:"senderEmail"` SenderName string `json:"senderName"` Message string `json:"message"` } func SendEmail(emailReq EmailRequest) error { auth := smtp.PlainAuth("", "myemail@gmail.com", "swnhmrwnqfrsrdqo", "smtp.gmail.com") msg := fmt.Sprintf("From:\r%s\nName:\r%s\nMessage:\r%s\n", emailReq.SenderEmail, emailReq.SenderName, emailReq.Message) err := smtp.SendMail("smtp.gmail.com:587", auth, "myemail@gmail.com", []string{"myemail@gmail.com"}, []byte(msg)) if err != nil { return err } return nil } func Email(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { w.Header().Set("Allow", "POST") w.WriteHeader(405) w.Write([]byte("Method Not Allowed")) return } var emailReq EmailRequest if err := json.NewDecoder(r.Body).Decode(&emailReq); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Bad Request")) return } if err := SendEmail(emailReq); err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("Internal Server Error")) log.Printf("Error with the SendEmail func execution: %v", err) return } w.WriteHeader(http.StatusOK) w.Write([]byte("Email sent successfully")) } func main() { c := cors.New(cors.Options{ AllowedOrigins: []string{"https://cihanbatasul.com"}, AllowedMethods: []string{http.MethodPost}, AllowCredentials: true, }) mux := http.NewServeMux() mux.HandleFunc("/email/", Email) handler := c.Handler(mux) log.Print("Listening on port :8080") err := http.ListenAndServe(":8080", handler) log.Fatal(err) }
错误截图

解决方案
从错误来看,核心是CORS跨域请求被阻止,结合代码细节,按以下步骤修复:
完善后端CORS配置
- 确认前端域名完全匹配:如果前端实际访问地址是
https://www.cihanbatasul.com,需将其加入AllowedOrigins数组; - 添加允许的请求头:前端请求携带了
Content-Type: application/json,需在CORS配置中补充AllowedHeaders: []string{"Content-Type"},确保该头被许可。
修改后的CORS配置示例:
c := cors.New(cors.Options{ AllowedOrigins: []string{"https://cihanbatasul.com", "https://www.cihanbatasul.com"}, AllowedMethods: []string{http.MethodPost}, AllowedHeaders: []string{"Content-Type"}, AllowCredentials: true, })- 确认前端域名完全匹配:如果前端实际访问地址是
解决HTTPS/HTTP混合访问问题
前端用HTTPS请求后端的https://ip:8080,如果后端容器未配置HTTPS证书,会导致连接失败,间接触发CORS错误。建议:- 给后端配置HTTPS证书(如Let's Encrypt);
- 在GoDaddy服务器上配置Nginx反向代理,将
https://cihanbatasul.com/api/email/转发到后端容器的8080端口,前端改用同域名HTTPS请求,彻底避免跨域。
优化前端请求地址配置
不要硬编码ip:8080,改用环境变量配置API地址。比如在React项目的.env文件中设置:REACT_APP_API_URL=https://cihanbatasul.com/api/email/代码中通过
process.env.REACT_APP_API_URL获取地址,提升部署灵活性。验证Gmail SMTP配置(可选)
若后端发送邮件失败,也可能导致请求异常。确认Gmail应用密码swnhmrwnqfrsrdqo有效,且已开启两步验证、允许应用密码访问。
内容的提问来源于stack exchange,提问作者intero
相关产品推荐
相关产品推荐

