登录
首页 >  Golang >  Go问答

Golang 服务器接收 JavaScript POST 请求时发生 JSON 输入意外结束错误

来源:stackoverflow

时间:2024-02-09 14:33:26 367浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Golang 服务器接收 JavaScript POST 请求时发生 JSON 输入意外结束错误》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在 javascript 中向我的 go 服务器发出 post 请求以 post 一些 json 数据。后台成功接收数据。

如果我控制台记录承诺的结果,我会在调用 fetchresponse.json() 的行处收到 unexpected end of json input 错误。我不明白为什么会发生这种情况。

javascript

const 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))
}

正确答案


我的问题是没有将响应发送回浏览器,因此它无法解析任何 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
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>