2011-12-23 75 views
0

這是(使用fetch的NodeJS和骨幹獲取

var MyModel = Backbone.Model.extend(); 
    var MyCollection = Backbone.Collection.extend({ 
     url: '/questions', 
     model: MyModel 
    }); 
    var coll = new MyCollection(); 
    coll.fetch({ 
     error: function (collection, response) { 
      console.log('error', response); 
     }, 
     success: function (collection, response) { 
      console.log('success', response); 
     } 
    }); 

我的前端代碼,這是(使用app.get

app.get('/questions', function (request, response) { 
    console.log('Inside /questions'); 
    response.writeHead(200, { 
     'Content-Type': 'text/json' 
    }); 
    response.write('{test:1}'); 
    response.end(); 
}); 

的問題我的後端代碼是,雖然響應如預期的那樣,調用客戶端error回調。當我刪除行response.write('{test:1}');時,調用success回調。任何想法,我可能做錯了什麼?

回答

4

那麼{test:1}是無效的JSON。

{ "test":"1" } OR { "test":1 } 然而,這些嘗試之一代替。

鍵是JSON中的字符串,並且JSON中的字符串必須用雙引號括起來,查看JSON.org以獲取更多信息。

爲確保您擁有有效的JSON用於更復雜的對象只是使用JSON.stringify()

var obj = { test : 1 }; 
response.write(JSON.stringify(obj)); //returns "{"test":1}" 

此外,correct Content-Type for jsonapplication/json

+0

非常感謝!這確實是個問題。 – Randomblue 2011-12-23 15:32:52

+0

有沒有辦法瞭解有關錯誤的更多信息?在將來,我希望被告知這是JSON是無效的...... – Randomblue 2011-12-23 15:34:36

+0

我不是一個大'node.js'或'backbone'的人。我猜想錯誤響應中有一些信息;如果沒有,我會發布另一個問題,對不起.. – Chad 2011-12-23 15:36:34

1

如果你使用的表達,你需要res.send將自動轉換對象轉換成JSON。如果你擔心它,有一個叫res.json的新東西可以將任何東西轉換成JSON。

var obj = {super: "man"} 
res.send(obj) // converts to json 
res.json(obj) // also converts to json 

您不需要writeHead(),write()或end()。

http://expressjs.com/guide.html