我尝试使用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的值。
发布于 2017-01-17 03:51:27
Beego似乎只接受带有这个头文件的数据:'Content-Type': 'multipart/form-data',所以在我添加这个头文件之后,一切都正常了。因为我不知道如何使用axios来实现这一点,所以我切换到了vue-resource,这是适用于Beego的示例代码:
this.$http.post("/", {test: "test"}, {
emulateJSON: true
});现在您可以像这样打印它:
fmt.Println(this.GetString("test"))我希望这能帮助到一些人
发布于 2017-01-17 11:14:51
刚刚验证了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 FormData。Axios also accepts a FormData as data。
https://stackoverflow.com/questions/41680798
复制相似问题