Beego POST请求体始终为空

6

我正在使用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);
         }
     });

当superagent请求触发时,我可以在日志中看到路径被正确匹配。然而,c.Ctx.Input.RequestBody始终为空。 我尝试使用其他工具比如Postman发送请求,但是没有成功。在GET请求中,我能够正确获取查询参数。 有什么提示或建议可以帮助修复或调试此问题吗?

1
你能进行HTTP捕获以确保请求体不为空吗? - Jiang YD
嗨哟,你觉得我该怎么做呢?在 Chrome 的开发者网络控制台中,我已经检查了一下请求体是否包含有效载荷,例如{"code": "123"},但是在 Beego 上打印整个请求时它是空的 :( - rawfish.dev
你打印出了 Received [] 吗? - Jiang YD
@JiangYD 是的,当尝试使用JSON主体时,它似乎总是为空。但是,我尝试将标题更改为.set('Content-Type', 'application/x-www-form-urlencoded'),然后我可以在c.Ctx.Input.Request.Form.Get("code")中检索字段。有什么想法是这种情况吗? - rawfish.dev
为什么你没有设置Content-Type为json呢?我看到你的代码中有.set('Accept', 'application/json'),但没有Content-Type - Jiang YD
在原始帖子中我漏掉了这一点,但实际上我已经尝试过了,但没有成功。我已经从beego转移到gin,完全相同的superagent代码可以完美地工作。不知道我还做错了什么,但似乎为了一个简单的json POST解包而调试太费力了。谢谢你的尝试! - rawfish.dev
1个回答

17
你需要在配置文件 "conf/app.conf" 中配置 "copyrequestbody = true"。
默认值为 false,因此内容不会复制到 c.Ctx.Input.RequestBody。
示例在文档的 "Retrieving data from request body" 部分中显示。 (http://beego.me/docs/mvc/controller/params.md)

1
这是解决方案! - lionelmessi
1
你不知道我为了得到这个答案而搜索了多少次谷歌! - TDo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接