【发布时间】:2015-12-16 11:47:45
【问题描述】:
我在节点 [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);
});
}
这是我的问题: 我能够将响应从节点 js 发送到角度 js,但如何解析它?如果我没有在文档之前添加“响应...:”,那么我会收到错误消息“第一个参数应该是字符串或缓冲区”。在角度上,我得到如下响应:->
response...:{_id:....1, prop1: 'a',prop2: 'b',prop3: 'c'},
{_id:....2, prop1: 'ab',prop2: 'bc',prop3: 'cd'}
我想将文档显示为表格格式
【问题讨论】:
-
发送
json而不是plain string喜欢:res.write({'response':docs}); -
仍然得到同样的错误'第一个参数应该是一个字符串或缓冲区'
-
您实际上可以设置 Content-Type:'application/json' 。如果您在此之后遇到相同的错误,请执行 res.send(JSON.stringify(docs));
标签: javascript angularjs node.js mongodb