无法在Go中获取Angular/Restangular表单数据

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

Cannot get Angular/Restangular form data in Go

问题

我有一个正常工作的Go REST服务,我可以使用Chrome REST插件获取表单数据。
我需要从我的Angular应用程序获取表单数据到服务端,到目前为止我还无法弄清楚。

我的Angular代码:

<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid}">
    <label>Drug Name</label>
    <input type="text" name="drugName" ng-model="drug.name" required>
      <span ng-show="myForm.drugName.$error" class="help-inline">
                                                    Required</span>
</div>
<a href="#/" class="btn">Cancel</a>
<button ng-click="save()" ng-disabled="isClean() || myForm.$invalid"
                                        class="btn btn-primary">Save</button>
<button ng-click="destroy()" ng-show="project._id"
                                        class="btn btn-danger">Delete</button>
</form>

我的app.js中的CreateCtrl,我设置了 RestangularProvider.setBaseUrl('/rest/v1');

function CreateCtrl($scope, $location, Restangular) {
$scope.save = function() {
    Restangular.all('drugs/').post($scope.drug).then(function(project) {
        $location.path('/list');
    });
}
}

在我的Go代码中,我使用gorilla,以下是相关部分:

http.Handle("/rest/v1/drugs/", drugs.MakeMuxer("/rest/v1/drugs/"))
func MakeMuxer(prefix string) http.Handler {

log.Println("**** drugs.MakeMuxer(): " + prefix);

var m *mux.Router

// 如果有前缀,则传递前缀。
if prefix == "" {
	m = mux.NewRouter()
} else {
	m = mux.NewRouter().PathPrefix(prefix).Subrouter()
}


m.HandleFunc("/", CreateDrug).Methods("POST")

// 其他所有请求都应该返回404。
//m.HandleFunc("/{path:.*}", gorca.NotFoundFunc)

return m
}

func CreateDrug(w http.ResponseWriter, r *http.Request) {

log.Println("**** CreateDrug.... ");
log.Println("drugName: " + r.FormValue("drugName"))
//c := appengine.NewContext(r)

}

我可以看到POST请求进入了"CreateDrug"函数,但是r.FormValue("drugName")是空的(当我使用浏览器的REST插件并将"drugName"设置为某个值时,它不为空)。

英文:

I have a Go rest service that works fine, I can get form data using a Chrome REST plugin.
I need to get form data from my Angular app to the service, and so far I cannot figure it out.

My Angular code:

&lt;form name=&quot;myForm&quot;&gt;
&lt;div class=&quot;control-group&quot; ng-class=&quot;{error: myForm.name.$invalid}&quot;&gt;
    &lt;label&gt;Drug Name&lt;/label&gt;
    &lt;input type=&quot;text&quot; name=&quot;drugName&quot; ng-model=&quot;drug.name&quot; required&gt;
      &lt;span ng-show=&quot;myForm.drugName.$error&quot; class=&quot;help-inline&quot;&gt;
                                                    Required&lt;/span&gt;
&lt;/div&gt;
&lt;a href=&quot;#/&quot; class=&quot;btn&quot;&gt;Cancel&lt;/a&gt;
&lt;button ng-click=&quot;save()&quot; ng-disabled=&quot;isClean() || myForm.$invalid&quot;
                                        class=&quot;btn btn-primary&quot;&gt;Save&lt;/button&gt;
&lt;button ng-click=&quot;destroy()&quot; ng-show=&quot;project._id&quot;
                                        class=&quot;btn btn-danger&quot;&gt;Delete&lt;/button&gt;
&lt;/form&gt;

My app.js CreateCtrl, I set RestangularProvider.setBaseUrl(&#39;/rest/v1&#39;);:

function CreateCtrl($scope, $location, Restangular) {
$scope.save = function() {
    Restangular.all(&#39;drugs/&#39;).post($scope.drug).then(function(project) {
        $location.path(&#39;/list&#39;);
    });
}
}

In my Go code, I am using gorilla, and here are the pertinent parts:

http.Handle(&quot;/rest/v1/drugs/&quot;, drugs.MakeMuxer(&quot;/rest/v1/drugs/&quot;));
func MakeMuxer(prefix string) http.Handler {

log.Println(&quot;**** drugs.MakeMuxer(): &quot; + prefix);

var m *mux.Router

// Pass through the prefix if we have one.
if prefix == &quot;&quot; {
	m = mux.NewRouter()
} else {
	m = mux.NewRouter().PathPrefix(prefix).Subrouter()
}


m.HandleFunc(&quot;/&quot;, CreateDrug).Methods(&quot;POST&quot;)

// Everything else should 404.
//m.HandleFunc(&quot;/{path:.*}&quot;, gorca.NotFoundFunc)

return m
}

func CreateDrug(w http.ResponseWriter, r *http.Request) {

log.Println(&quot;**** CreateDrug.... &quot;);
log.Println(&quot;drugName: &quot; + r.FormValue(&quot;drugName&quot;))
//c := appengine.NewContext(r)

}

I can see that the POST is getting into "CreateDrug", but r.FormValue(&quot;drugName&quot;) is empty (it is not empty when I use a browser rest plugin and set "drugName" to some value.

答案1

得分: 0

在调用r.FormValue之前,你需要调用r.ParseForm()

//编辑

在查阅了AngularJS之后,我注意到它将数据发送为JSON格式,所以你需要使用json.NewDecoder示例

type Drug struct {
    Name string `json:"drugName"`
}
func CreateDrug(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    var d Drug
    dec := json.NewDecoder(r.Body)
    dec.Decode(&d)
    log.Println("**** CreateDrug.... ")
    log.Println("drugName:", d.Name)
}
英文:

You need to call r.ParseForm() before you can call r.FormValue.

//edit

After looking up angularjs, I noticed it sends the data as json, so you have to use json.NewDecoder, example:

type Drug struct {
	Name string `json:&quot;drugName&quot;`
}
func CreateDrug(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	var d Drug
	dec := json.NewDecoder(r.Body)
	dec.Decode(&amp;d)
	log.Println(&quot;**** CreateDrug.... &quot;)
	log.Println(&quot;drugName:&quot;, d.Name)
}

huangapple
  • 本文由 发表于 2014年7月6日 09:15:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/24591870.html
匿名

发表评论

匿名网友

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

确定