0

代码一切正常,页面呈现,但我收到一大堆错误,在 res.render调用之前只有数据集的第一行被写入控制台。

Error: Can't set headers after they are sent.    
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
    at ServerResponse.header      (C:\Node\NodeTestTed\nodetestted\node_modules\express\lib\response.js:718:10)

    at ServerResponse.contentType (C:\Node\NodeTestTed\nodetestted\node_modules\
    express\lib\response.js:551:15)
    at ServerResponse.send (C:\Node\NodeTestTed\nodetestted\node_modules\express
    \lib\response.js:138:14)
    at done (C:\Node\NodeTestTed\nodetestted\node_modules\express\lib\response.j
    s:957:10)
        at Object.exports.renderFile (C:\Node\NodeTestTed\nodetestted\node_modules\j
    ade\lib\index.js:374:12)
        at View.exports.__express [as engine] (C:\Node\NodeTestTed\nodetestted\node_
    modules\jade\lib\index.js:417:11)
        at View.render (C:\Node\NodeTestTed\nodetestted\node_modules\express\lib\vie
    w.js:126:8)
        at tryRender (C:\Node\NodeTestTed\nodetestted\node_modules\express\lib\appli
    cation.js:639:10)
        at EventEmitter.render (C:\Node\NodeTestTed\nodetestted\node_modules\express
    \lib\application.js:591:3)
    GET /stylesheets/style.css 304 1.596 ms - -

res.render is called immediatly after the first row is returned from Tedious

这是代码:

var express = require('express');
var Promise = require('promise');

var router = express.Router();

/* GET home page. */
router.get('/', getClients, function(req, res, next) {
  console.log("one");
  res.render('index', { title: 'Hi There. ' });
});

router.get('/helloworld', function(req, res) {
    res.render('helloworld', {title: 'Hello World'});

});



function getClients(req, res, next) {
    var promise = new Promise(function(fulfill, reject){
    var dataset = [];

    var Connection = require('tedious').Connection;
    var Request = require('tedious').Request;
    var config = {
        server: '****',
        userName: '*****',
        password: '****',
        options: {
            instanceName: '****'
        }
    };

    var connection = new Connection(config);

    connection.on('connect', function (err) {
        if (err) {
            console.log(err);
            //res.statusCode = 500;
            // return res.json({ errors:[err] });
        } else {
            // If no error, then good to go...

            executeStatement();
            //console.log("hi");
        }
    });

    function executeStatement() {
    //var promise = new Promise(function(resolve, reject){


     var sql = "select people.people_id, evolv_cs.dbo.formatname(people.last_name, people.first_name, people.middle_name) as client " +
          " from  evolv_cs.dbo.people  join evolv_cs.dbo.event_log " +
          "on event_log.people_id = people.people_id " +
          " and event_log.event_definition_id = 'BA7EF74D-142D-4884-981A-6153755DFBE9' " + // program enrollment
          " and event_log.program_providing_service = '1D955DBF-529C-42D3-A2DA-C77B2036F642' " +   // Central Star PHF - Adolescent
          "  where   event_log.end_date is null ";

     var Request = require('tedious').Request;
     request = new Request(sql, function (err, rowCount) {
          if (err) {
               console.log(err);
               //callback(err);
               reject(err);
          } else {
           if(rowCount < 1) {
               callback(null, false);
           }
           else {
               //callback (null, newdata);
            fulfill(dataset);
           }
          }
     });


     request.on('row', function (columns) {

          columns.forEach(function (column) {
               console.log(column.value);

               dataset.push({
                col: column.metadata.colName,
                   val: column.value
               });
          });
          //newdata.push(dataset);
          //req.Clients = dataset;
          //req.body = dataset;
         // console.log(req.body);



          next();


     });


     request.on('doneProc', function (rowCount, more, returnStatus, rows) {
          //console.log('What TF');
          /*  arlen = values.length;
            for (i = 0; i < arlen; i++) {
                 console.log(values[i]); 
            }   */

          connection.close()
          console.log('zzz');


       //arr = values;
       //   console.log(arr[0]);

     });
     connection.execSql(request);
    // return resolve(dataset);   
    //});
     }
  });
    //console.log(dataset);

    // end of getclients

}



module.exports = router;
4

1 回答 1

0

这是因为你在next()里面打电话request.on('row', ...。当您调用 next 时,它会将控制权返回给 express 以调用下一个中间件函数。

您传递给的函数 request.on('row', ...将为您的查询返回的每一行调用一次。您真的只想在next()获得所有结果后打电话。

因此,您需要将next()调用移至如下内容:

request.on('done', function (rowCount, more, rows) {
  // process rows
  next(null, rows);
});
于 2016-11-17T00:13:13.010 回答