无法从ajax请求获取Golang中的post参数
问题描述:
On the client side I have code:
let response = await fetch('/getInfo', {
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify({filename: "file.jpg"})
});
Code on the server side:
fmt.Println(c.PostForm("filename")) // empty
Why is it empty? How to get value of c.PostForm("filename")?
在客户端,我有以下代码: p>
让响应 =等待fetch('/ getInfo',{
凭证:'same-origin',
方法:'POST',
主体:JSON.stringify({filename:“ file.jpg”})
}) ;
code> pre>
服务器端代码: p>
fmt.Println(c.PostForm(“ filename”) )//空
code> pre>
为什么为空? 如何获取c.PostForm(“ filename”)的值? p>
div>
答
This code decodes JSON object from request body:
// 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
}