Answer the question
In order to leave comments, you need to log in
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>
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));
}
}
})
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
Well, it seems like you first need to do r.ParseMultipartForm() or r.ParseForm() and then you can already r.FormValue("123")
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 questionAsk a Question
731 491 924 answers to any question