這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
最近用angular替換我blog的部分頁面。結果悲劇的發現,post請求到revel以後,revel的ParamsFilter解析不粗來參數。
看了下請求資訊,發現jquery和angular的post請求是有些不同的。
jquery的content type是application/x-www-form-urlencoded,會把post的參數拼接到url上,格式如foo=bar&baz=moe這樣的。
而angular裡,預設content type 是application/json,資料是以json格式發過去的。
但是在revel的params.go裡面,沒有對json格式的請求做參數處理。
用作者的原話說,這個json的處理沒有什麼用,而且在controller裡用encoding/json處理也只是幾行代碼的事情。所以,就沒有所以了。。。
關於這個問題的解決方案,有很多,可以從angular層面解決,把angular的post請求也按照jquery的方法做些改變,如下:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
https://github.com/petersirka/total.js/issues/26
也可以從revel服務端解決。
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"} )