我正在尝试设置一个简单的 Mongoose 测试服务器,该服务器读取用户集合中的用户并打印用户名。我似乎无法让 res.write 查询数据显示在客户端
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'bugtraq');
var schema = mongoose.Schema({ username : 'string', email : 'string' });
var User = db.model('User', schema);
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
User.find().exec(function (err, users) {
if(err) { res.write(err.message); }
if(users) {
users.forEach(function(u){
console.log(u.username);
return '<b>'+u.username+'</b>';
});
}
});
res.write('</body></html>');
res.end();
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
服务器端输出为
<html><head></head><body></body></html>
我确实在控制台输出中看到了用户名
欢迎任何指点
最佳答案
你有两个问题。首先, Mongoose 查询是任意同步的,但在查询实际发生之前,您将在回调之外结束响应(我必须重新缩进代码以确保)。
要使其正常工作,您需要在 User.find
的回调函数内结束响应。
其次,您没有按照您的想法收集输出。这行是错误的:
return '<b>'+u.username+'</b>';
您将查找的输出返回
到稀薄的空气中。如果您想在响应中返回它,您需要捕获它。
把它们放在一起,可能看起来像这样:
User.find().exec(function (err, users) {
if(err) { res.write(err.message); }
if(users) {
// here make a buffer to store the built output ...
var output = [];
users.forEach(function(u){
// (you saw this console output because this loop is happening, it's
// just happening after your response has been ended)
console.log(u.username);
// ... then in each iteration of the loop, push to the buffer
output.push('<b>'+u.username+'</b>');
});
}
// finally, finish the response in the `find` callback.
res.end(output.join() + '</body></html>');
});
关于node.js - mongoose.js 服务器 - 查询数据的 res.write 不会将数据发送回客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434974/