Not able to receive JS xhr POST

script.js

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

main.go

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 http://127.0.0.1:8080/public/ 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.

main.go

package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
)

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

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

	log.Println("starting")
	http.ListenAndServe("127.0.0.1:8080", nil)
}

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

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

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

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

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

public/index.html

<!DOCTYPE html>
<html>
<head>
	<script src="/public/script.js"></script>
</head>
<body>
	<p>hello</p>
</body>
</html>

public/script.js

var xhr = new XMLHttpRequest();
xhr.open("POST", "/db", true);
var data = {foo: "bar"};
xhr.send(JSON.stringify(data));
2 Likes

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.