Pau*_*nes 5 post json http go eof
我不断收到 EOF 错误,但不知道为什么。我使用 print 语句进行检查,方法是 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
}
}
Run Code Online (Sandbox Code Playgroud)
它只打印出“Bob”和“EOF”,我已经做了一些广泛的谷歌搜索,但我真的找不到这个问题在其他地方的答案,我也尝试过使用 r.ParseForm 并使用 r.FormValue 和 PostFormValue,但是当我这样做的字符串是空的。
另外,如果它有用,这里是值的前端代码
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ "path": "example/path/to" })
})
Run Code Online (Sandbox Code Playgroud)
编辑:这是我的转储请求
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"}
Run Code Online (Sandbox Code Playgroud)
让我感到困惑的是 EOF 错误出现在 DumpRequest 消息之间。
因此,问题似乎在于我的前端调用端点两次,这就是发生 EOF 错误的原因。我把我的所有代码都包装在
if r.Method == "POST" {
...
}
Run Code Online (Sandbox Code Playgroud)
并且问题已经解决。
我相信额外的端点命中是 CORS 飞行前的事情或其他事情。
归档时间: |
|
查看次数: |
8481 次 |
最近记录: |