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;
Don't call res.send()
and res.end()
in the same request handler.
res.send()
will call res.end()
for you ( source ). res.end()
is typically used after calling multiple res.write()
.
If /user POST is called multiple times and the POST n doesn't close the connection with db.close(); before the n+1 POST you could get the same error.
Just solved on my script.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.