亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JavaScript POST 請求到 Golang 服務器錯誤 - JSON 輸入意外結束

JavaScript POST 請求到 Golang 服務器錯誤 - JSON 輸入意外結束

Go
暮色呼如 2022-11-23 14:21:16
我正在用 JavaScript 向我的 Go 服務器發出 POST 請求以發布一些 JSON 數據。后端成功接收數據。如果我控制臺記錄 promise 的結果,我會在調用fetchResponse.json()的行收到Unexpected end of JSON input error 。我不知道為什么會這樣。JavaScriptconst sendScore = async () => {    try {        const fetchResponse = await fetch(`http://localhost:8000/sendscore`, {            method: 'POST',            headers: {                'Accept': 'application/json',                'Content-Type': 'application/json'            },            body: JSON.stringify({name:"kris"})        });        const data = await fetchResponse.json();        return data;    } catch (e) {        return e;    }}const sendScoreBtn = document.querySelector("#sendScoreBtn");sendScoreBtn.addEventListener("click", () => {    console.log("Sending score...")    const res = sendScore()    res.then(console.log)})Go /sendscore 端點處理程序func recieveScore(w http.ResponseWriter, r *http.Request) {    var res playerScore    if err := json.NewDecoder(r.Body).Decode(&res); err != nil {        fmt.Println("Line 31", err)    }    fmt.Println("Res", res)}func main() {    // Serve static files(js, css)    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))    http.HandleFunc("/", homePage)    http.HandleFunc("/sendscore", recieveScore)    fmt.Println("Server started. Listening on port :8000")    log.Fatal(http.ListenAndServe(":8000", nil))}
查看完整描述

1 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

我的問題是沒有將響應發送回瀏覽器,因此它無法解析任何 JSON。更新了 Go 處理程序,使該過程正常運行。


func recieveScore(w http.ResponseWriter, r *http.Request) {

    var res playerScore

    if err := json.NewDecoder(r.Body).Decode(&res); err != nil {

        fmt.Println("Line 31", err)

    }


    fmt.Println("Res", res)

    

    w.Header().Set("Content-Type", "application/json")

    json.NewEncoder(w).Encode(res) // Writing the result to response

}


查看完整回答
反對 回復 2022-11-23
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號