问题
I tried crud Operation using node js and mongodb.all crud operation working fine.but i tried to run get method its showing on;y one record.after i see my code its throwing error (Can't set headers after they are sent).How to solve this issue any one give suggestion.
index.js
router.get('/', async (req, res,next) => {
(async function() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = client.db('olc_prod_db');
let r = await db.collection('Ecommerce').find();
r.forEach(function(result,err)
{
res.send(result)
})
// Close connection
client.close();
} catch(err) {
console.log(err.stack);
}
})();
});
回答1:
router.get('/', async (req, res,next) => {
(async function() {
try {
await client.connect();
console.log("Connected correctly to server");
const db = db.collection('Ecommerce').find({}).toArray(function(error, documents) {
if (err) throw error;
res.send(documents);
});
} catch(err) {
console.log(err.stack);
}
})();
});
For each subsequent request, you have to 'send' once only. This method just completes the request cycle so you can't call it on loop because of loop run 'n' time.
回答2:
No need in forEach
, just do:
const r = await db.collection('Ecommerce').find({}).toArray();
res.send({ data: r })
来源:https://stackoverflow.com/questions/55812098/i-tried-crud-operation-using-nodejs-and-mongodb-all-crud-operation-is-working-f