【问题标题】:Read a post parameter sent through axios in golang在golang中读取一个通过axios发送的post参数
【发布时间】:2021-08-22 05:49:16
【问题描述】:

我是 golang 的新手,并尝试理解这一点。我面临以下问题。

我正在发送axios 的帖子如下

const options = {
  data: {
    test: this.state.value,
  },
  method: 'POST',
  url: `/test`,
};
console.log(options)
axios.request(options).then(
  () => {
    console.log(this.state.value);
  },
  (error) => {
    console.log(error);
  },
);

现在在 Go 部分,我正在尝试阅读它。但我不知道如何在 Go 中阅读它。我尝试使用以下代码,但它不起作用。它只打印test Value。谁能帮我?谢谢。

func routetest(w http.ResponseWriter, r *http.Request) {
    test, _ := param.String(r, "test")
    fmt.Printf("test Value")
    fmt.Printf(test)
    fmt.Printf("test Value")
}

更新代码

func routeTest(w http.ResponseWriter, r *http.Request) {
    type requestBody struct {
        test string `json:"test"`
    }
    body := requestBody{}
    decoder := json.NewDecoder(r.Body)
    if err := decoder.Decode(&body); err != nil {
        // some error handling
        return
    }
    defer r.Body.Close()
    test := body.test
    fmt.Printf(test)
}

【问题讨论】:

    标签: javascript go post axios request


    【解决方案1】:

    最简单的方法是将你的 body 解码为类似 json 的结构,然后从那里获取你的值

    import (
        "encoding/json"
        "fmt"
        "net/http"
    )
    
    type requestBody struct {
        Test       string `json:"test"`
    }
    
    func routeTest(w http.ResponseWriter, r *http.Request) {
        body := requestBody{}
        decoder := json.NewDecoder(r.Body)
        if err := decoder.Decode(&body); err != nil {
            // some error handling
            return
        }
        defer r.Body.Close()
        test := body.Test
        fmt.Printf(test)
    }
    

    【讨论】:

    • 感谢您的快速回复。我已经使用了您的代码(请检查说明,我已将其粘贴在那里)仍然没有得到它的价值。你能检查一次吗?谢谢:)
    • 注意:requestBody 结构的test 字段应该被导出
    • @Matteo 我没听懂你。如何导出?
    • @Rich 使变量在golang中可导出,它应该用大写字母命名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2022-01-18
    • 2021-05-22
    • 2020-07-02
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    相关资源
    最近更新 更多