B.Y B.Y - 5 months ago 25
Node.js Question

Need a way to set res object after couchbase DB call "Error: Can't set headers after they are sent"

var express = require('express');

var search = express.Router();

search.get('/', function(req, res, next) {
console.log('1');

dbCall(function(error, result) {
if (error) {
res.status(404).json();
} else {
res.json(result);
}
});

console.log('last');
next();
});

var dbCall = function(callback) {
var couchbase = require('couchbase');
var cluster = new couchbase.Cluster('couchbase://127.0.0.1');
var bucket = cluster.openBucket('default');

var doc;

var ViewQuery = couchbase.ViewQuery;

var query = ViewQuery.from('dev_test', 'allData');

bucket.query(query, function(err, viewResults) {
if (err) {
callback(err, null);
} else {
console.log('inqueryCall');
var results = viewResults;
callback(null, results);
console.log(results);
}
});
};

module.exports = search;


Here's the error that I get is :
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)


Can someone please explain the issue here(not just the solution)?

I've added console.log and the issue here is that the couchbase call to async

Answer

Remove next() call, that is causing this error. next() is used in middleware to pass the flow to next middleware or endpoint/route

search.get('/', function(req, res, next) {

   dbCall(function(error, result) {
       if (error) {
           res.status(404).json();
       } else {
           res.json(result);
       }
   });
});