douan8473 2016-12-17 05:18 采纳率: 100%
浏览 1255
已采纳

求助:解析POST请求中的req.body

我正在使用fetch API 将两个值发送到我的 POST 请求处理程序:

fetch('http://localhost:8080/validation', {
        method:'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email:this.state.email,
            password:this.state.password
        })

我想在服务器端保存电子邮件和密码为字符串,以下是我的尝试:

type credentials struct {
    Test string
}

func Validate(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {

    decoder := json.NewDecoder(req.Body)

    var creds credentials

    err := decoder.Decode(&creds)

    if err != nil {
        panic(err)
    }

    fmt.Println(creds.Test)
}

问题是我不知道发送到 POST 结构的确切格式。我正在尝试将 req.Body 保存为字符串,但是没有得到任何结果。

当输入 fmt.Println 只得到一个空格,解析它的正确方法是什么?

  • 写回答

2条回答 默认 最新

  • drvkf88226 2016-12-17 05:41
    关注

    Try with

    type credentials struct {
        Email string `json:"email"`
        Password string `json:"password"`
    }
    

    You are receiving a JSON with two values. Receiving struct should have a structure matching your request. Otherwise, there are no placeholders to decode the JSON into, as in your case - email and password do not have matching struct fields. Btw. if you send "Test" in your JSON, this would work, as you have a Test field in your struct!

    Regarding field names. If fields in JSON do not start with a capital letter or even have different names, then you should use so called tags. More on tags: https://golang.org/pkg/encoding/json/#Marshal

    In my example I used them to match struct field names to your json fields, i.e. to make email from json match Email field of the credentials struct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!