React向Golang后端发送JSON表单数据时出现400错误求助
解决React前端向Golang Echo后端发送JSON数据的400 Bad Request问题
问题描述
使用React开发的前端向Golang Echo框架编写的后端发送JSON表单数据时,出现POST http://localhost:9091/xxxx 400 (Bad Request)错误,尝试修改Content-Type为application/json后仍未解决。
前端提交代码:
const response = await fetch('http://localhost:9091/rewardAdmin/v1/rewardRule/createRewardInfo', { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'text/plain' }, body: JSON.stringify(formData.formData), });
后端处理代码:
func (rc *RewardAdminController) CreateRewardInfo(ctx echo.Context) error { var rewardInfo rewardInfo.RewardInfoRequest if err := ctx.Bind(&rewardInfo); err != nil { return ctx.JSON(http.StatusBadRequest, err.Error()) } result, err := rc.RewardRuleService.CreateRewardInfo(rewardInfo) if err != nil { return ctx.JSON(http.StatusBadGateway, err.Error()) } return ctx.JSON(http.StatusOK, result) }
解决方案
1. 移除mode: 'no-cors'配置
no-cors模式会限制浏览器的跨域请求行为:无法设置application/json类型的请求头,后端无法正确识别并解析JSON数据;同时浏览器会屏蔽响应内容,无法获取请求结果。跨域需求应通过后端配置CORS中间件实现,而非使用no-cors模式。
2. 修正前端请求配置
将请求头设置为application/json,确保发送的是标准JSON格式数据:
const response = await fetch('http://localhost:9091/rewardAdmin/v1/rewardRule/createRewardInfo', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData.formData), // 若需要携带Cookie,添加该行 // credentials: 'include', });
3. 后端配置CORS中间件
在Echo框架中添加CORS中间件,允许前端域名的跨域请求:
import ( "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) func main() { e := echo.New() // 配置CORS,替换AllowOrigins为你的React前端域名 e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ AllowOrigins: []string{"http://localhost:3000"}, AllowMethods: []string{echo.GET, echo.POST, echo.PUT, echo.DELETE}, AllowHeaders: []string{echo.HeaderContentType, echo.HeaderAuthorization}, })) // 注册路由 e.POST("/rewardAdmin/v1/rewardRule/createRewardInfo", rc.CreateRewardInfo) e.Start(":9091") }
4. 确保结构体字段标签正确
后端RewardInfoRequest结构体需要添加json标签,与前端发送的JSON字段名对应,否则ctx.Bind无法正确解析数据:
type RewardInfoRequest struct { RuleName string `json:"ruleName"` // 对应前端JSON中的ruleName字段 RewardAmount int `json:"rewardAmount"` // 其他字段同理添加json标签 }
5. 调试排查
- 使用Postman直接调用后端接口,验证后端逻辑是否正常
- 在浏览器开发者工具的Network面板,检查请求的Payload和Headers,确认JSON数据格式正确、
Content-Type为application/json - 打印后端
err.Error()的具体内容,定位是字段缺失、类型不匹配还是格式错误
内容的提问来源于stack exchange,提问作者Akhil T Sam
相关产品推荐
相关产品推荐

