【问题标题】:Beego POST request body always emptyBeego POST 请求正文始终为空
【发布时间】: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


【解决方案1】:

需要在配置文件“conf/app.conf”中配置“copyrequestbody = true”。

默认为 false,因此内容不会复制到 c.Ctx.Input.RequestBody。

该示例显示在文档中的“从请求正文中检索数据”部分。 (http://beego.me/docs/mvc/controller/params.md)

【讨论】:

  • 这就是解决方案!
  • 你不知道我为了得到这个答案做了多少谷歌搜索!