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

我不断收到 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,但是当我这样做字符串是空的。


另外,如果它有用,这里是价值的前端代码


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 消息之间。


慕妹3242003
浏览 716回答 1
1回答

回首忆惘然

因此,问题似乎在于我的前端两次调用端点,这就是发生 EOF 错误的原因。我把我所有的代码都包装在了if r.Method == "POST" {  ...  }并且问题已经解决。我相信额外的端点命中是 CORS 飞行前的事情或其他东西。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go