为了账号安全,请及时绑定邮箱和手机立即绑定

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条经验 获得超6个赞

我的问题是没有将响应发送回浏览器,因此它无法解析任何 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 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信