【问题标题】:Beego not accepting ajax paramsBeego 不接受 ajax 参数
【发布时间】:2017-01-16 16:26:00
【问题描述】:

我正在尝试使用 VueJS 向使用 Beego 框架 (GoLang) 编写的应用程序发出简单的 POST 请求,但该应用程序看不到任何输入请求。当我使用标准表单请求(无 ajax)时,一切都很好。 这是我的 VueJS 代码:

storePost: function(event) {
    axios.post("/api/posts/store", {body: "test"}).then(function(response) {
        if (response.data.status == 200) {
            this.posts.push(response.data.data);
        }else {
            console.log("error");
        }
    }, function(response){
        console.log("error");
    });
}

这是我的 Beego 代码:

// router.go
beego.Router("/api/posts/store", &controllers_API.PostsController{}, "post:Store")

// PostsController.go
func (this *PostsController) Store() {
    fmt.Println(this.GetString("body"))

    // some irrelevant code which handles the response...
}

fmt.Println 总是不打印任何内容。当我使用标准表单时,fmt.Println 可以毫无问题地打印出body 的值。

【问题讨论】:

  • 您能在开发者工具下的网络选项卡中看到负载流量吗?只是为了确保有实际数据发送到服务器。
  • 没有beego专家,但是如果你跨域可能还需要一个head方法端点
  • @Sombriks 我查了,有数据,{body: "test"}
  • @RickyA 不是跨域的,我在本地测试一下
  • 在同一个端口上?

标签: ajax go vue.js beego


【解决方案1】:

Beego 似乎只接受带有此标头的数据:'Content-Type': 'multipart/form-data' 所以在我添加该标头后一切正常。 因为我不知道如何使用 axios 来做到这一点,所以我切换到 vue-resource,这是与 Beego 一起使用的示例代码:

this.$http.post("/", {test: "test"}, {
    emulateJSON: true
});

现在你可以像这样打印它:

fmt.Println(this.GetString("test"))

我希望这对某人有所帮助

【讨论】:

    【解决方案2】:

    刚刚验证 axios 和 vue-resource 默认使用application/json。您在此处使用的emulateJSON tells vue-resource to use application/x-www-form-urlencoded。您可能只需要在beego 中进行json 解码,因为它默认将请求正文视为urlencoded

    multipart/form-data 工作可能是因为它已经存在很长时间了(比如urlencoded),所以beego 默认会识别它。要使用 vue-resource 发布 multipart/form-data 请求:use FormDataAxios also accepts a FormData as data.

    【讨论】:

      猜你喜欢
      • 2016-06-14
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 2016-10-05
      • 2016-10-31
      • 2018-03-16
      • 2023-04-03
      相关资源
      最近更新 更多