我一直在用NodeJS,ExpressJS和AngularJS做一些工作。傳遞/路由包含函數原型的對象
我目前正在開發一個圖形繪製項目,需要在後端完成所有的處理,所以前端只顯示結果。這需要我將包含數據和函數原型的一些對象路由到前端。到目前爲止,我在這最後一部分沒有任何運氣。當我從前端調用$http.get
時,我的路由以res.send(object)
響應,在節點後端的console.log
中,對象打印完成其原型函數,但在前端的瀏覽器中,檢索到的對象僅打印數據/文本部分,並完全丟棄所有功能。
請參見下面的代碼片段,以獲得要點:
sample backend ExpressJS routes code snippet
// let's create an object,
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
// a function prototype
this.fooBar = function(){
return 'Yes';
}
};
// open up a route
app.get('/getObject', function(req, res){
var baby = new Person("John", "Doe");
console.log(baby)
//this console logs the following, as expected:
// Person { firstName: 'John', lastName: 'Doe', fooBar: [Function] }
// respond with the entire object
res.send(baby)
});
sample front end AngularJS code snippet
$http.get('/getObject')
.success(function(data){
console.log(data)
// THIS, however, only console logs the data, and discards the function
// Object {firstName: "John", lastName: "Doe"}
})
.error(function(err){
console.log(err)
});
這讓我抓我的頭,試圖找出問題是否是由Express/Node,還是從Angular的結尾,或者兩者兼而有之?我非常感謝這方面的一些幫助,因爲我非常喜歡將整個對象(包括原型函數)傳遞到前端以用於一些最小化的操作。如果這是不可能的,至少指向一個合適的解決方法:-)。謝謝!
通過線路發送可執行腳本通常是一個壞主意。我建議你重新考慮你的設計。您的前端只能接收數據,最好使用JSON格式。 – kennasoft
我知道設計有些東西,但只是想知道它是否可能。似乎這種方法可能是不可靠的...... –