doukanxi4246 2018-12-30 15:09
浏览 421
已采纳

无法从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")?

  • 写回答

1条回答 默认 最新

  • duanfangbunao36970 2018-12-30 15:45
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法