Not able to receive JS xhr POST


var xhr = new XMLHttpRequest();“POST”, “/db”, true);
var data = {foo: “bar”};


func main() {
http.HandleFunc("/db", database)
http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir(“public”))))
http.ListenAndServe(":8080", nil)

func database(w http.ResponseWriter, r *http.Request) {
// tried playing all sort of cat_and_mouse opts here with r
// r.Method is POST but can’t retrieve info sent

I have no clue how to proceed with this, can’t retrieve any info its all empty and I am pretty sure this is the right approximation to getting the data.

Any hints?

Just to add that the rest works: css/html and sending data from go to the browser

What did you try?

What you need to do is read the request body.

As @calmh said, on the Go side you need to read the request body.

You also need to send something useful, like JSON. I modified script.js to do that. The JSON can then be unmarshaled on the server side.

Assuming I understand what you are trying to do, I got something working. Put the files in their correct places, then compile and run main.go. Directing your web browser to will first get public/index.html and then public/script.js. The script will run, sending an XHR request to func database, which will print out the resulting data to the terminal.


package main

import (

func main() {
	log.SetFlags(log.Lshortfile | log.Ltime)

	http.HandleFunc("/db", database)
	http.Handle("/public/", http.StripPrefix("/public", http.FileServer(http.Dir("public"))))

	http.ListenAndServe("", nil)

type Data struct {
	Foo string `json:"foo"`

func database(w http.ResponseWriter, r *http.Request) {

	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)

	var data Data
	err = json.Unmarshal(b, &data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)

	log.Printf("%#v", data)


<!DOCTYPE html>
	<script src="/public/script.js"></script>


var xhr = new XMLHttpRequest();"POST", "/db", true);
var data = {foo: "bar"};

If you use separate domains, must implement CORS

Guys it did work thanks :slight_smile: Followed the pattern showed by @nathankerr and tailored to my app and is working nice. Took me a while to come back because wanted to make sure everything was alright in my end.

Thanks a lot everyone!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.