简体   繁体   English

发送一个 JSON 数组作为来自 Node.js 的响应

[英]Send a JSON array as response from Node.js

I am fetching data from a MongoDB database then putting it in a cursor to send that as a Node.js response.我正在从 MongoDB 数据库中获取数据,然后将其放入游标中以将其作为 Node.js 响应发送。

var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
/* GET users listing. */
router.get('/', function(req, res, next) {
  //res.send('respond with a resource');
  MongoClient.connect(url, function(err, db) {
    var cursor = db.collection('Employee').find();
    cursor.each(function(err, doc) {

      console.log(doc);
      arrayres = doc ;
     res.send(doc);

    });
    db.close();
  });
});

module.exports = router;

It sends only the first record then I get this error:它只发送第一条记录,然后我收到此错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
    at ServerResponse.removeHeader (_http_outgoing.js:528:11)
    at ServerResponse.send 

Notice: I get this error only when there are multiple records to send as response.注意:只有当有多个记录作为响应发送时,我才会收到此错误。

You are sending the response twice.您发送了两次响应。 Which is impossible ( look at Why can't we do multiple response.send in Express.js? )这是不可能的(看看为什么我们不能在 Express.js 中做多个 response.send?

  res.send('respond with a resource');

Here and这里和

res.send(arrayres);

Here.这里。

Here is a working example based on jeremy's answer :这是一个基于 jeremy's answer 的工作示例:

router.get('/', function (req, res, next) {
    MongoClient.connect(url, function (err, db) {
        var cursor = db.collection('Employee').find();

        let employees = []
        const pushData = async () => {
            cursor.forEeach( function (doc) {
                employees.push(doc);
            });
        }
        const sendResponse = async () => {
            await pushData();
            res.json(employees);
        }
    });
});

You can only send back one response to the browser (be it res.send() , res.end() , res.sendFile() , res.json() or any other).您只能向浏览器发送一个响应(可以是res.send()res.end()res.sendFile()res.json()或任何其他)。 So, you can't have that inside a .forEach() .所以,你不能把它放在.forEach()里面。

First, build an array, then send your data back once.首先,构建一个数组,然后将数据发送回一次。

router.get('/', function (req, res, next) {
    MongoClient.connect(url, function (err, db) {
        var cursor = db.collection('Employee').find();

        let employees = []

        cursor.forEeach( function (doc) {
            employees.push(doc);
        });

        res.json(employees);
    });
});

Or with Mongoose :或与猫鼬:

Employee.find().lean().exec( (err,docs) => res.json(docs))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM