Today I run into a little issue as I tried to POST to a Go backend using Axios but I could not get the parameters I was sending.

I was doing this:

func handleReq(w http.ResponseWriter, req *http.Request) {
	err := req.ParseForm()
	if err != nil {
		panic(err)
	}
	v := req.Form
	owner := req.Form.Get("owner")
	name := req.Form.Get("name")
    //...
}

but the two parameters I was looking for were not available. Why?

Turns out that I was assuming Axios sent the parameters using Content-Type:application/x-www-form-urlencoded BUT it’s not, it’s using Content-Type:application/json

This means that to access the parameters I need to decode them using json.Decoder.

Here is some sample code that does the trick:

type myData struct {
	Owner string
	Name  string
}

func handleAddNewRepo(w http.ResponseWriter, req *http.Request) {
	decoder := json.NewDecoder(req.Body)

	var data myData
	err := decoder.Decode(&data)
	if err != nil {
		panic(err)
	}

	owner := data.Owner
	name := data.Name
    //...
}

Want to hire me?

I'm currently considering remote job/contract opportunities as a Frontend Developer.

Read more about me and if you're interested, get in touch.