我有一个带有效负载的HTTP POST请求
indices=0%2C1%2C2
Run Code Online (Sandbox Code Playgroud)
这是我的golang后端代码
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Println("r.PostForm", r.PostForm)
log.Println("r.Form", r.Form)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Println("r.Body", string(body))
values, err := url.ParseQuery(string(body))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Println("indices from body", values.Get("indices"))
Run Code Online (Sandbox Code Playgroud)
输出:
r.PostForm map[]
r.Form map[]
r.Body indices=0%2C1%2C2
indices from body 0,1,2
Run Code Online (Sandbox Code Playgroud)
为什么POST请求不被解析r.ParseForm(),而manaully解析它url.ParseQuery(string(body))会给出正确的结果?
Not*_*fer 14
问题不在你的服务器代码中,这很好,但只是你的客户端,无论它是什么,都缺少Content-TypePOST表单的正确标题.只需将标题设置为
Content-Type: application/x-www-form-urlencoded
Run Code Online (Sandbox Code Playgroud)
在你的客户.
从您的 http.Request 使用 PostFormValue("params") 从您的参数中获取值
err := r.ParseForm()
if err != nil{
panic(err)
}
params := r.PostFormValue("params") // to get params value with key
Run Code Online (Sandbox Code Playgroud)