无法从 ajax 请求中获取 Golang 中的 post 参数
Can't get post parameter in Golang from ajax request
在客户端我有代码:
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
}
在客户端我有代码:
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
}