在客户端我有代码:
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")
的值?
最佳答案
此代码从请求正文中解码 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
}
关于ajax - 无法从ajax请求中获取Golang中的post参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53978746/