【发布时间】:2025-12-12 09:30:01
【问题描述】:
我正在使用 Beego 的便捷方法来解析请求正文值,并且具有以下功能:
路由器文件:
apiNamespace := beego.NewNamespace("/api")
apiNamespace.Router("/sessions/google/new", &controllers.SessionsController{}, "get:GoogleNewSession")
beego.AddNamespace(apiNamespace)
控制器代码:
func (c *SessionsController) URLMapping() {
c.Mapping("GoogleNewSession", c.GoogleNewSession)
}
func (c *SessionsController) GoogleNewSession() {
// Always serve JSON
defer func() {
c.ServeJson()
}()
// This is always blank
log.Printf("'Received %+v'", c.Ctx.Input.RequestBody)
c.Ctx.ResponseWriter.WriteHeader(200)
return
// truncated
}
前端JS(超级代理):
request
.post('/sessions/google/new')
.use(prefix)
.send({ code: authCode })
.set('Accept', 'application/json')
.end(function(err, res){
console.log("******* request", res.request)
if (res.ok) {
var body = res.body;
console.log('yay got ' + JSON.stringify(res.body));
} else {
console.log("***** err", err);
console.log("***** not ok", res.text);
}
});
当超级代理请求触发时,我可以在日志中看到路径正在正确匹配。但是,c.Ctx.Input.RequestBody 始终为空。
我尝试使用其他东西来触发请求,例如 Postman,但无济于事。在 GET 请求中,我能够正确检索查询参数。
有任何线索或建议可帮助解决或调试此问题吗?
【问题讨论】:
-
您能否进行 HTTP 捕获以确保请求正文不为空?
-
嘿,你建议我怎么做?在 chrome 的开发人员网络控制台中,我检查了正文是否包含有效负载,例如 {"code": "123"} 但是在 Beego 上打印整个请求时它是空的:(
-
所以你得到了 print
Received []? -
@JiangYD 是的,当尝试使用 JSON 正文时,它似乎总是空的。但是,我尝试将标题更改为
.set('Content-Type', 'application/x-www-form-urlencoded'),并且能够检索c.Ctx.Input.Request.Form.Get("code")中的字段。知道为什么会这样吗? -
那为什么不将 content-type 设置为 json 呢?我看到了你的代码
.set('Accept', 'application/json'),但没有看到Content-Type。
标签: http go superagent beego