简体   繁体   中英

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

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);
       }
   });
});

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.

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