
Beego 默认无法直接解析 Axios 发送的 JSON 格式 POST 请求体,需通过设置 Content-Type: application/x-www-form-urlencoded 或启用表单模拟,才能使 this.GetString() 正常读取参数。
beego 默认无法直接解析 axios 发送的 json 格式 post 请求体,需通过设置 `content-type: application/x-www-form-urlencoded` 或启用表单模拟,才能使 `this.getstring()` 正常读取参数。
在使用 Vue.js(如通过 Axios)向 Beego 后端发起 AJAX POST 请求时,常见问题表现为 this.GetString("key") 始终返回空字符串——即使前端明确传入了数据。这是因为 Beego 的 GetString() 方法默认仅解析 URL 查询参数(GET)和标准表单编码(application/x-www-form-urlencoded 或 multipart/form-data)的请求体,而 Axios 默认以 application/json 格式发送 JSON 数据,Beego 不会自动解析该格式的请求体为表单字段。
✅ 正确做法是:让 Axios 模拟传统表单提交行为,而非发送原始 JSON。可通过以下任一方式实现:
方式一:使用 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 全局转换器(适用于全站统一处理)
// 在入口文件中设置
axios.defaults.transformRequest = [(data, headers) => {
if (data && typeof data === 'object' && !headers['Content-Type']) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
return new URLSearchParams(data).toString();
}
return data;
}];
对应 Beego 控制器保持不变,即可正常获取:
func (c *PostsController) Store() {
body := c.GetString("body") // ✅ 现在能正确输出 "test"
if body == "" {
c.Data["json"] = map[string]interface{}{"status": 400, "msg": "missing body"}
c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{"status": 200, "data": body}
c.ServeJSON()
}
⚠️ 注意事项:
- ❌ 避免直接发送
axios.post(url, { body: "test" })(默认 JSON),Beego 不解析; - ❌ 不要手动设置
Content-Type: multipart/form-data并传入 JSON 对象——这会导致边界解析失败; - ✅ 若必须使用 JSON 格式,应在 Beego 中改用
c.RequestBody手动解码:var req struct{ Body string `json:"body"` } json.Unmarshal(c.Ctx.Input.RequestBody, &req) - Beego 路由注册需确保方法匹配:
beego.Router("/api/posts/store", &controllers_API.PostsController{}, "post:Store")
总结:Beego 与现代前端框架协作的关键在于请求体编码格式对齐。优先采用 application/x-www-form-urlencoded + URLSearchParams 方案,兼顾兼容性、可读性与 Beego 原生支持能力。











