Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

I am making a POST request in JavaScript to my Go server to POST some JSON data. The backend recieves the data succesfully.
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))
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda