0

Im developing a small IOT device for my home running in a PI. The server (running in Go) hosts a web interface which should be able to do tasks in realtime (eg. pressing a button should change the sound output by the pi without reloading the page)

Im trying to send a post request from my web interface to the pi so that the requests can be handled in realtime by the server application. I want to do this without reloading the page. I used Javascript fetch to do this:

document.getElementById("buttons_form").addEventListener("submit", function(e) {
    e.preventDefault();
    const formData = new FormData(this); // IDEALLY this would be done without a form

    fetch("/change-sound", { method: "POST", body: formData });

My server responds to the request. When using fmt.Println(r.Form), the output is just map[]. Request.Body gives &{0xc000298060 <nil> <nil> false true {0 0} false false false 0x69cd20}. This is the rough go code I have at the moment:

func ChangeSound(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        return
    }

    err := r.ParseForm()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(r.Form)
}

When I use the form normally instead of sending the post request via javascript, the request form in go gives the expected map with all of the form variables (but of course there is no way to do this without reloading, plus I want to have sliders etc that would work in realtime as well which a form would not work for)

How can I send an arbitrary post request using javascript that will be able to be parsed by the server? I'm fairly new to both go and web-development.

Tjk
  • 11
  • 2
  • I don't think that you are sending the request right. Take a look at this answer: https://stackoverflow.com/a/37562814/5712794 You are sending a post form, but ParseForm in the docs specifies: ```For other HTTP methods, or when the Content-Type is not application/x-www-form-urlencoded, the request Body is not read, and r.PostForm is initialized to a non-nil, empty value.``` – Nikola Jokic Oct 16 '22 at 09:09
  • How about looking at the Dev Console and inspect what you are sending in the body?! I bet your FormData object does not serialize into a nice JSON os similar. ;-) – Draško Kokić Oct 16 '22 at 14:16

0 Answers0