S
S
starosta462018-12-14 15:08:18
go
starosta46, 2018-12-14 15:08:18

How to get POST request data in golang?

There is a simple page with a button and a text field:

<!DOCTYPE html>
<html>  
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>




<div id="demo">
  <button v-on:click="upload">Получить данные</button>
  <div v-if="loading">Loading...</div>
  <p>{{result}} </p>
  <section v-if="errored">
    <p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
  </section>
  
</div>

<script src="main1.js"></script>
</html>

By clicking on the button using axios, a POST request is sent to the golang server. The request comes in, the data is sent back and successfully processed on the page. However, I cannot read the page request data to the server on the server. What could be the reason?
js file:
var demo = new Vue({
    el: '#demo',
    data: {
        loading: false,
        errored: false,
        result: "no data"
    },
    methods: {
        upload: function () {
            this.loading = true;
            axios
                .post('http://localhost:8000',{123: "123"})
                .then(response => {
                    this.result = response;
                })
                //.then(response => console.log(response))
                .catch(error => {
                    console.log(error)
                    this.errored = true;
                })


                .finally(() => (this.loading = false));




        }
    }
})

Server:
package main

import (
  "fmt"
  "net/http"
)

func receiveSend(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Access-Control-Allow-Origin", "*")
  w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

  if r.Method == "POST" {

    fmt.Println("My request is: ", r.FormValue("123"))
    fmt.Fprintln(w, "тут валидный json ")

  }
}
func main() {

  http.HandleFunc("/", receiveSend)

  http.ListenAndServe(":8000", nil)
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey Stupenkov, 2018-12-15
@starosta46

https://stackoverflow.com/questions/47630163/axios...

P
Pavel Shvedov, 2018-12-14
@mmmaaak

and if you look in r.Body ?

A
Ao, 2018-12-14
@darknefrit

Well, it seems like you first need to do r.ParseMultipartForm() or r.ParseForm() and then you can already r.FormValue("123")

D
Dasha Tsiklauri, 2018-12-14
@dasha_programmist

you need to set content-type application/x-www-form-urlencoded on the client side, otherwise you send json , and see what FormValue does, json is not a form !

axios.post('http://localhost:8000',{123: "123"}, {headers:{'Content-Type':'application/x-www-form-urlencoded'}})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question