
Beego 默认无法直接解析 Axios 发送的 JSON 格式 AJAX 请求体,需通过设置 Content-Type: application/x-www-form-urlencoded 或启用表单模拟,才能使 this.GetString() 正常获取参数。
beego 默认无法直接解析 axios 发送的 json 格式 ajax 请求体,需通过设置 `content-type: application/x-www-form-urlencoded` 或启用表单模拟,才能使 `this.getstring()` 正常获取参数。
在使用 Vue.js(或其他前端框架)向 Beego 后端发起 AJAX POST 请求时,一个常见误区是默认以 JSON 格式发送数据(如 axios.post(url, {body: "test"})),此时请求体为 application/json,而 Beego 的 this.GetString()、this.Input().Get() 等方法仅从表单数据(form)和 URL 查询参数中提取值,并不会自动解析原始 JSON Body。
Beego 不会主动解码 application/json 请求体——它只解析 application/x-www-form-urlencoded 和 multipart/form-data 两种编码格式下的键值对。因此,当 Axios 默认以 JSON 方式提交时,this.GetString("body") 始终返回空字符串。
✅ 正确做法是:让前端以表单编码方式提交数据,而非原始 JSON。以下是几种可靠方案:
✅ 方案一:Axios 启用 URLSearchParams(推荐)
storePost() {
const params = new URLSearchParams();
params.append('body', 'test');
axios.post('/api/posts/store', params, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
if (response.data.status === 200) {
this.posts.push(response.data.data);
}
})
.catch(err => console.error('Request failed:', err));
}
✅ 方案二:Axios 配置 transformRequest(兼容旧版)
axios.post('/api/posts/store', { body: 'test' }, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: [(data, headers) => {
return Object.keys(data)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k]))
.join('&');
}]
});
✅ 方案三:后端主动读取 JSON Body(更灵活,需额外解析)
若必须使用 JSON 提交(如 RESTful 设计),Beego 可通过 this.Ctx.Input.RequestBody 获取原始字节,再手动解码:
// PostsController.go
func (this *PostsController) Store() {
var req struct {
Body string `json:"body"`
}
if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
this.Data["json"] = map[string]interface{}{"status": 400, "message": "Invalid JSON"}
this.ServeJSON()
return
}
fmt.Println("Received body:", req.Body) // ✅ 正确输出 "test"
// 继续业务逻辑...
this.Data["json"] = map[string]interface{}{"status": 200, "data": req}
this.ServeJSON()
}
⚠️ 注意:此时不能再用 this.GetString("body"),必须走 JSON 解析路径。
? 补充说明
-
emulateJSON: true(vue-resource)本质就是将 JS 对象序列化为x-www-form-urlencoded字符串,并设置对应 header; - Beego 的
GetString()仅作用于ParseForm()解析后的表单缓存,该缓存默认在 GET/POST 请求中自动触发,但仅对支持的 Content-Type 生效; - 若使用
multipart/form-data(如上传文件),需确保前端正确构造 FormData,Beego 同样可直接GetString()获取字段。
总结:前后端内容类型需严格匹配。优先推荐 方案一(URLSearchParams) ——简洁、标准、无需引入额外库,且与 Beego 表单处理机制天然契合。











