在客户端,我有代码:
let response = await fetch('/getInfo', {
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify({filename: "file.jpg"})
});
服务器端代码:
fmt.Println(c.PostForm("filename")) // empty
为什么它是空的?如何获取c.PostForm(“ filename”)的值?
答案 0 :(得分:1)
此代码从请求正文中解码JSON对象:
// Request is structure to encode request body
type Request struct {
FileName string `json:"filename"`
}
// ServeHTTP is request handler
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var req Request
err := decoder.Decode(&req)
if err != nil {
// handle error
return
}
// process request
}