如何在angular中解析mongodb数据的node-js响应

How to parse node js response of mongodb data in angular?

本文关键字:数据 mongodb node-js 响应 angular      更新时间:2023-09-26

我在节点[not express]中有一个http服务器。点击按钮,我有一个get方法,然后从mongodb(使用mongoose)中提取文档,并将其显示在有角度的页面上。

点击按钮:

       $http.get('/get').success(function(response){
         console.log(response);
       //logic to store JSON response of database and perform repeat to display each document returned on UI
       });

在使用http.createServer而不是express创建服务器的节点代码中:

     if(req.url==="/get"){
      res.writeHead(200,{'content-type':'text/plain'});
      modelName.find({}, 'property1 prop2 prop3', function(err,docs){
        res.write('response...:  '+docs);
       });
     }

这是我的问题:我可以将响应从node js发送到angular js,但如何解析它?如果我不添加"response…:"在docs之前,我收到一条错误消息"第一个参数应该是字符串或缓冲区"。在角度上,我得到的响应如下:->

      response...:{_id:....1, prop1: 'a',prop2: 'b',prop3: 'c'},
      {_id:....2, prop1: 'ab',prop2: 'bc',prop3: 'cd'}

我想将文档显示为表格格式

我不知道你的确切设置,但我认为你应该传输application/json而不是text/plain

不能简单地将字符串连接到docs,只需要返回docs(作为数组传输)或写入res.write({'response':docs})(作为对象传输)。

考虑从$http转移到资源服务。在资源服务中,如果要作为对象传输,则需要将isArray设置为false;如果要作为数组传输,则需将其设置为true:https://docs.angularjs.org/api/ngResource/service/$resource