JavaScript POST请求到Golang服务器出错 – JSON输入意外结束

huangapple go评论121阅读模式
英文:

JavaScript POST request to Golang server error - Unexpected end of JSON input

问题

我正在为您翻译以下内容:

我正在使用JavaScript向我的Go服务器发出POST请求,以POST一些JSON数据。后端成功接收到数据。如果我在控制台记录promise的结果,我会得到Unexpected end of JSON input错误,该错误发生在调用**fetchResponse.json()**的行上。我无法弄清楚为什么会发生这种情况。

JavaScript

  1. const sendScore = async () => {
  2. try {
  3. const fetchResponse = await fetch(`http://localhost:8000/sendscore`, {
  4. method: 'POST',
  5. headers: {
  6. 'Accept': 'application/json',
  7. 'Content-Type': 'application/json'
  8. },
  9. body: JSON.stringify({name:"kris"})
  10. });
  11. const data = await fetchResponse.json();
  12. return data;
  13. } catch (e) {
  14. return e;
  15. }
  16. }
  17. const sendScoreBtn = document.querySelector("#sendScoreBtn");
  18. sendScoreBtn.addEventListener("click", () => {
  19. console.log("Sending score...")
  20. const res = sendScore()
  21. res.then(console.log)
  22. })

Go /sendscore 端点处理程序

  1. func recieveScore(w http.ResponseWriter, r *http.Request) {
  2. var res playerScore
  3. if err := json.NewDecoder(r.Body).Decode(&res); err != nil {
  4. fmt.Println("Line 31", err)
  5. }
  6. fmt.Println("Res", res)
  7. }
  8. func main() {
  9. // Serve static files(js, css)
  10. http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
  11. http.HandleFunc("/", homePage)
  12. http.HandleFunc("/sendscore", recieveScore)
  13. fmt.Println("Server started. Listening on port :8000")
  14. log.Fatal(http.ListenAndServe(":8000", nil))
  15. }
英文:

I am making a POST request in JavaScript to my Go server to POST some JSON data. The backend recieves the data succesfully. <br>
If I console log the result of the promise I get Unexpected end of JSON input error at line where fetchResponse.json() is called. I cant figure out why it is happening.

JavaScript

  1. const sendScore = async () =&gt; {
  2. try {
  3. const fetchResponse = await fetch(`http://localhost:8000/sendscore`, {
  4. method: &#39;POST&#39;,
  5. headers: {
  6. &#39;Accept&#39;: &#39;application/json&#39;,
  7. &#39;Content-Type&#39;: &#39;application/json&#39;
  8. },
  9. body: JSON.stringify({name:&quot;kris&quot;})
  10. });
  11. const data = await fetchResponse.json();
  12. return data;
  13. } catch (e) {
  14. return e;
  15. }
  16. }
  17. const sendScoreBtn = document.querySelector(&quot;#sendScoreBtn&quot;);
  18. sendScoreBtn.addEventListener(&quot;click&quot;, () =&gt; {
  19. console.log(&quot;Sending score...&quot;)
  20. const res = sendScore()
  21. res.then(console.log)
  22. })

Go /sendscore endpoint handler

  1. func recieveScore(w http.ResponseWriter, r *http.Request) {
  2. var res playerScore
  3. if err := json.NewDecoder(r.Body).Decode(&amp;res); err != nil {
  4. fmt.Println(&quot;Line 31&quot;, err)
  5. }
  6. fmt.Println(&quot;Res&quot;, res)
  7. }
  8. func main() {
  9. // Serve static files(js, css)
  10. http.Handle(&quot;/static/&quot;, http.StripPrefix(&quot;/static/&quot;, http.FileServer(http.Dir(&quot;./static&quot;))))
  11. http.HandleFunc(&quot;/&quot;, homePage)
  12. http.HandleFunc(&quot;/sendscore&quot;, recieveScore)
  13. fmt.Println(&quot;Server started. Listening on port :8000&quot;)
  14. log.Fatal(http.ListenAndServe(&quot;:8000&quot;, nil))
  15. }

答案1

得分: 0

我的问题是没有将响应发送回浏览器,因此无法解析任何JSON。
更新了Go处理程序,使该过程正常工作。

  1. func recieveScore(w http.ResponseWriter, r *http.Request) {
  2. var res playerScore
  3. if err := json.NewDecoder(r.Body).Decode(&res); err != nil {
  4. fmt.Println("Line 31", err)
  5. }
  6. fmt.Println("Res", res)
  7. w.Header().Set("Content-Type", "application/json")
  8. json.NewEncoder(w).Encode(res) // 将结果写入响应
  9. }
英文:

My problem was not sending response back to the browser and therefore it couldnt parse any JSON.
Updated Go handler, which made the process work.

  1. func recieveScore(w http.ResponseWriter, r *http.Request) {
  2. var res playerScore
  3. if err := json.NewDecoder(r.Body).Decode(&amp;res); err != nil {
  4. fmt.Println(&quot;Line 31&quot;, err)
  5. }
  6. fmt.Println(&quot;Res&quot;, res)
  7. w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
  8. json.NewEncoder(w).Encode(res) // Writing the result to response
  9. }

huangapple
  • 本文由 发表于 2022年3月15日 20:18:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/71482119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定