Beego不接受ajax params

时间:2017-01-16 16:26:01

标签: ajax go vue.js beego

我正在尝试使用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的值没有问题。

2 个答案:

答案 0 :(得分:0)

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

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

现在您可以像这样打印:

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

我希望这有助于某人

答案 1 :(得分:0)

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

multipart/form-data可能因为它已经存在很长时间(例如urlencoded),因此默认情况下它会识别它。要使用vue-resource发布multipart/form-data请求:use FormDataAxios also accepts a FormData as data

相关问题