i'm trying to fetch some data from a HTML Webpage via Javascript to my Golang Webserver. But the Data does'nt seem to be received there.
This is my Javascript Function, which is called, when selecting something in my dropdown menu of my webpage:
async function onDataFormatSelect(dataFormat)
{
console.log('Change DataFormat', dataFormat);
let formDataSelect = new FormData();
formDataSelect.append("cmd", "change");
const fetchoptions = {
method: 'POST',
body: formDataSelect,
};
let r = await fetch('/myURL', fetchoptions);
console.log('HTTP response code.', r.status);
for (var pair of formDataSelect.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
}
In SetupRoutes() in my Go Webserver, the URL gets an Handler:
http.HandleFunc("/myURL", urlHandler)
This is my Handler:
func urlHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseForm()
topicName := r.FormValue("topicName")
cmd := r.FormValue("cmd")
log.Println("action: " + cmd)
switch cmd {
...
case "change": //Change DataFormat of Topic
log.Println("cmd is " + cmd)
newDataFormat := r.FormValue("dataFormat")
//Call another function
default:
log.Println("unknown command: " + cmd)
}
} else {
log.Println("using wrong method (GET)")
}
http.Redirect(w, r, appdata.Status.ProxyRedirect, http.StatusMovedPermanently)
}
The Output of Javascript is correct. The FormDataSelect is filled correctly, but in Go the "cmd" is not there. Somehow in another Function with the same setup everything is working correctly.
Can you help me or do you have any Workaround for me beside using XMLHttpRequest?
fetchwill set the Content-Type header automatically based on the content. ForFormDataobjects it will set it to be multipart and will get the mandatoryboundaryparameter which we can't predict from the code.