gpt4 book ai didi

json - 从http请求解码json时出现EOF错误

转载 作者:行者123 更新时间:2023-12-01 22:22:03 24 4
gpt4 key购买 nike

我不断收到 EOF 错误,我不知道为什么。我使用打印语句进行检查,方法是 POST,内容类型是预期的 application/json。
我期待的 json 看起来像这样 { "path": "example/path/to"}
代码成功运行,但打印出一个错误,这也很奇怪,因为它应该在完成函数的其余部分之前返回一个错误

func create(w http.ResponseWriter, r *http.Request) {   
dump, er := httputil.DumpRequest(r, true)
if er != nil {
http.Error(w, fmt.Sprint(er), http.StatusInternalServerError)
return
}
fmt.Println(string(dump))

var req map[string]string
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&req)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(req["path"])

err = os.MkdirAll("/"+req["path"], os.ModePerm)
if err != nil {
fmt.Println(err)
return
}
}
它只打印出“Bob”和“EOF”,我已经做了一些广泛的谷歌搜索,但我真的无法在其他任何地方找到这个问题的答案
我也尝试过使用 r.ParseForm 并使用 r.FormValue 和 PostFormValue,但是当我这样做时,字符串是空的。
此外,如果它有用,这里是值(value)的前端代码
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ "path": "example/path/to" })
})
编辑:这是我的 DumpRequest
Listening on :5000
OPTIONS /api/create HTTP/1.1
Host: localhost:5000
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site

EOF
POST /api/create HTTP/1.1
Host: localhost:5000
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 47
Content-Type: application/json
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
{"path":"/Users/paul/Desktop/temp/new/hi 2/hi"}
令我困惑的是 EOF 错误出现在 DumpRequest 消息之间。

最佳答案

因此,问题似乎是我的前端两次调用端点,这就是发生 EOF 错误的原因。我把我的代码的所有代码都包裹在

if r.Method == "POST" {
...
}
并且问题已经解决。
我相信额外的端点命中是 CORS 飞行前的事情或其他事情。

关于json - 从http请求解码json时出现EOF错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com