无法在Golang中访问POST请求的参数。

huangapple go评论84阅读模式
英文:

unable to access post request params in golang

问题

我正在尝试在Golang中访问通过jQuery Ajax发送的post参数。也许我漏掉了一些明显的东西。以下是我的代码片段:

<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

    <script>
        $('form').submit(function(e) {
            e.preventDefault();
            var jsn = {
                vvv: $("#textinput").val()
            };
            console.log(jsn);
            $.ajax({
                type: "POST",
                async: true,
                url: "/homepage",
                data: jsn,
                processData: true,
                contentType: "application/json",
                cache: false,
            }).done(function(response){
                $("#resultdiv").html(response);
            });
        });
    </script>
</head>
</html>

这是我的Golang代码:

func MainConversion(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    text := r.FormValue("vvv")
    fmt.Fprint(w, string(text))
    return
}

我尝试过f.formValue()r.Form.Get()。提前感谢您的帮助。

英文:

I am trying to access post params in golang which are sent via jquery ajax. Maybe I am missing something obvious. Here are my code snippets

<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

    $(&#39;form&#39;).submit(function(e) {
        e.preventDefault();
        var jsn = {
            vvv = $(&quot;#textinput&quot;).val();   
        };
        console.log(jsn);
        $.ajax({
            type: &quot;POST&quot;,
            async : true,
        //enctype: &#39;multipart/form-data&#39;,
        url: &quot;/homepage&quot;,
        data: jsn,
        processData: true,
        contentType: &quot;application/json&quot;,
        cache: false,
    }).done(function(response){
        $(&quot;#resultdiv&quot;).html(response);
    });
});

</script>

here is my golang code:

 func MainConversion(w http.ResponseWriter, r *http.Request) {
     r.ParseForm()    
        text := r.FormValue(&quot;vvv&quot;)
        fmt.Fprint(w, string(text))
        return
    })

I have tried f.formValue(), r.Form.get() . Thanks in advance

答案1

得分: 3

你已经发送了一个带有JSON主体的请求,但是ParseForm*http.Request上不能处理JSON。你需要读取请求的主体并将其解析为JSON,或者不要将主体发送为JSON。

func MainConversion(w http.ResponseWriter, r *http.Request) {
    var body = make(map[string]string)
    if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    text := body["vvv"]
    w.Write([]byte(text))
}
英文:

You've sent your request with a JSON body, but ParseForm on an *http.Request does not handle JSON. You need to read the body of the request and parse it as JSON, or don't send your body as JSON.

func MainConversion(w http.ResponseWriter, r *http.Request) {
    var body = make(map[string]string)
    if err := json.NewDecoder(r.Body).Decode(&amp;body); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    text := body[&quot;vvv&quot;]
    w.Write([]byte(text))
}

答案2

得分: 0

你的JS代码片段存在语法错误,所以我假设没有请求到达你的Golang API。

应该修改为:

var jsn = {
    vvv: $("#textinput").val()
};
英文:

Your JS snippet contains syntax errors, so I assume no request reaches your golang API.

var jsn = {
    vvv = $(&quot;#textinput&quot;).val();   
};

should be:

var jsn = {
    vvv : $(&quot;#textinput&quot;).val()
};

huangapple
  • 本文由 发表于 2017年9月16日 10:48:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/46249587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定