最近用angular替換我blog的部分頁面。結果悲劇的發現,post請求到revel之後,revel的ParamsFilter解析不粗來參數。jquery
看了下請求信息,發現jquery和angular的post請求是有些不一樣的。git
jquery的content type是application/x-www-form-urlencoded,會把post的參數拼接到url上,格式如foo=bar&baz=moe這樣的。angularjs
而angular裏,默認content type 是application/json,數據是以json格式發過去的。github
可是在revel的params.go裏面,沒有對json格式的請求作參數處理。ajax
用做者的原話說,這個json的處理沒有什麼用,並且在controller裏用encoding/json處理也只是幾行代碼的事情。因此,就沒有因此了。。。json
關於這個問題的解決方法,有不少,能夠從angular層面解決,把angular的post請求也按照jquery的方法作些改變,以下:app
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/post
https://github.com/petersirka/total.js/issues/26url
也能夠從revel服務端解決。code
https://github.com/robfig/revel/issues/97
本頁的代碼修改以下:
func (c *Task) NewTask() revel.Result { decoder := json.NewDecoder(c.Request.Body) var content ToDoContent if err := decoder.Decode(&content); err != nil { print(">>>err:", err) } else { print(">>>>content:", content.Content) } json.Marshal(content) return c.RenderJson(content) }
雖然這樣代碼確實很少,不過瞬間感受比rails弱爆了。。。
順帶的提一下,若是是jquery的請求,也須要稍微改動一下的,不然,revel同樣的解析不粗來。
在jquery裏要把post的jsonstringify一下。
具體參考這裏https://github.com/robfig/revel/issues/126
$.ajax({ type:"POST", url:"/Application/Index", data:JSON.stringify({ name: "John", time: "2pm" }), contentType:"application/json", dataType:"json" } )