在POST请求中解析req.body
我正在使用在POST请求中解析req.body,post,go,Post,Go,我正在使用fetchAPI向我的POST请求处理程序发送两个值 fetch('http://localhost:8080/validation', { method:'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({
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
时,我得到一个空白。解析它的正确方法是什么?req.Body
是一个io.Reader
,您可以使用它来排空:
data, err := ioutil.ReadAll(req.Body)
asString := string(data) // you can convert to a string with a typecast
但我不确定您试图将req.Body
保存为字符串是否就是这个意思
要将响应解析为数据结构,可以将其解组为*接口{}
类型的变量:
var creds interface{}
decoder.Decode(&creds)
然后检查值:
fmt.Printf("%#v\n", creds)
或者使用我觉得更容易阅读的语言
creds
变量将表示在主体中找到的JSON对象,对于您的示例输入,这将是一个map[string]接口{}
,有两个条目,可能都是字符串。比如:
map[string]interface{}{
"email": email_value,
"password": password_value,
}
然后用以下方法检查值:
email, ok := creds["email"].(string)
if ok {
// email will contain the value because creds["email"] passed the type check
fmt.Printf("submitted email is %#v\n", email)
} else {
// "email" property was a string (may be missing, may be something else)
}
在关于解组接口值的讨论中,解释了如何在不事先知道其结构的情况下解析任意JSON字符串的语义。尝试使用
type credentials struct {
Email string `json:"email"`
Password string `json:"password"`
}
您将收到一个包含两个值的JSON。接收结构应具有与您的请求匹配的结构。否则,就不会有占位符来解码JSON,就像您的情况一样-电子邮件和密码没有匹配的结构字段。顺便说一句,如果您在JSON中发送“Test”
,这将起作用,因为您的结构中有一个测试字段
关于字段名。如果JSON中的字段不以大写字母开头,甚至没有不同的名称,那么应该使用所谓的标记。
有关标签的更多信息:
在我的示例中,我使用它们将结构字段名称与json字段相匹配,即从json匹配
凭证
struct的电子邮件
字段。Fwiw,另一个答案更优,我误解了关于不确定结构是什么的部分,原始问题明确规定客户端代码由作者控制。