英文:
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
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))
}
英文:
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
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 endpoint handler
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
得分: 0
我的问题是没有将响应发送回浏览器,因此无法解析任何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) // 将结果写入响应
}
英文:
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.
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论