I'm trying get data from MongoDB in a Node.js file.
I'm getting this error:
/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:719:10)
at ServerResponse.json (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:247:10)
at ServerResponse.send (/home/jay/node_project/user_data_manag/node_modules/express/lib/response.js:152:21)
at /home/jay/node_project/user_data_manag/routes/api.js:42:13
at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:777:7
at handleCallback (/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:96:12)
at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:741:16
at handleCallback (/home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:96:12)
at /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/cursor.js:675:5
// Dependencies
var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
var objectId = require('mongodb').ObjectID;
var assert = require('assert');
var url = 'mongodb://localhost/rest_test';
router.post('/user', function(req, res, next) {
if (req.body.name == "Login") {
var result = [];
mongo.connect(url, function(err, db) {
var data = db.collection('products').find();
data.forEach(function(doc, err) {
result.push(doc);
}, function() {
db.close();
res.send({
iteamd: result
});
});
});
} else {
res.send("data");
}
res.end();
});
//insert data
router.post('/put-data', function(req, res, next) {
var item = {
title: req.body.name,
content: req.body.sku,
author: req.body.price
};
var data = req.body.name;
mongo.connect(url, function(err, db) {
var cursor = db.collection('products').find({
"name": data
});
res.send(cursor.toString);
});
});
// Return router
module.exports = router;