【问题标题】:Can't send an array of Javascript objects in node.js无法在 node.js 中发送 Javascript 对象数组
【发布时间】:2014-03-14 21:46:36
【问题描述】:

我有以下代码

app.get('/posts',function(req,res){

console.log(posts);
res.send(posts);
res.send(200);
});

我正在使用以下内容来获取和返回 js 对象的数组(posts 是数组)

App.PostsRoute = Ember.Route.extend({
model: function(){
    return $.ajax({
        url : '/posts',
        type : 'GET',
        success : function(data){
            return data;
        }
    });
}
});

所以当我用[ { body: "Hello" }, {body : "world" } ] 填充posts 数组时,我在控制台中得到以下输出:

而在我的应用程序中,模型没有渲染,而且我在 chrome 开发工具中看不到任何响应,这些是一些 ss

响应是空的,甚至不是 {} 。出了什么问题?我不认为Ember 有什么问题,毕竟我看不到回复!

【问题讨论】:

    标签: javascript arrays node.js ember.js express


    【解决方案1】:

    我认为问题的出现是因为您调用了两次res.send。只需评论这一行:

    res.send(200);
    

    不需要此行,因为 Express 会自动将状态代码设置为 200(或在某些情况下 - 304)。

    如果你想设置自己的状态码,只需写:

    res.status(someCode);
    

    如您所见here

    【讨论】:

    • 但是如果一个接一个使用res.send(200)res.json(obj)会起作用吗?
    • @user206032 我相信不会。但你也可以写res.json(200, obj);,或res.send(200, obj);
    【解决方案2】:

    几个问题:

    1. 您需要在发送对象之前对其进行 JSON.stringify。

    2. 尝试用这个代替 res.send:

      res.writeHead(200, {'Content-Type': 'application/json'});
      res.end(JSON.stringify(posts));
      
    3. 您要在哪里返回“数据”?你应该有一些回调函数,像这样:

      success:function(data) {
          handleData(data); 
      }
      

    【讨论】:

    • 数据作为postsRou​​te的模型返回,是Ember
    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 2021-01-15
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多