NodeJS发送回复时出错

时间:2015-09-09 01:56:58

标签: javascript node.js mongodb

我正在制作一个简单的Rest服务,它必须将数据添加到数据库(MongoDB)中JSON请求中的数据。当我向服务发出请求时出现问题,服务器因以下错误而停止运行:

  

controller@0.0.0启动C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller   节点./bin/www

     

{[错误:无法找到模块' ../ build / Release / bson']代码:' MODULE_NOT_FOUND' }   js-bson:使用纯JS版本无法加载c ++ bson扩展   POST / controller / addagent 200 25.762 ms - 0   _http_outgoing.js:335       抛出新错误('在发送后无法设置标头。');             ^   错误:发送后无法设置标头。       在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:335:11)       在ServerResponse.header(C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ node_modules \ express \ lib \ response.js:718:10)       在ServerResponse.send(C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ node_modules \ express \ lib \ response.js:163:12)       在Promise。 (C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ routes \ controller.js:26:15)       在Promise。 (C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ node_modules \ monk \ node_modules \ mpromise \ lib \ promise.js:178:8)       在Promise.emit(events.js:129:20)       在Promise.emit(C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ node_modules \ monk \ node_modules \ mpromise \ lib \ promise.js:84:38)       在Promise.fulfill(C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ node_modules \ monk \ node_modules \ mpromise \ lib \ promise.js:97:20)       在Promise.resolve(C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ node_modules \ monk \ node_modules \ mpromise \ lib \ promise.js:126:15)       在Immediate._onImmediate(C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ node_modules \ monk \ lib \ collection.js:343:23)

     

npm ERR! Windows_NT 6.3.9600   错误的ERR! argv" C:\ nodejs \\ node.exe" " C:\的NodeJS \ node_modules \ NPM \ BIN \ NPM-cli.js" "开始"   错误的ERR!节点v0.12.7   错误的ERR! npm v2.11.3   错误的ERR!代码ELIFECYCLE   错误的ERR! controller@0.0.0 start:node ./bin/www   错误的ERR!退出状态1   错误的ERR!   错误的ERR!在controller@0.0.0启动脚本&node;节点./bin/www'失败。   错误的ERR!这很可能是控制器包的问题,   错误的ERR!不是与npm本身。   错误的ERR!告诉作者你的系统失败了:   错误的ERR!节点./bin/www   错误的ERR!您可以通过以下方式获取信息:   错误的ERR! npm所有者ls控制器   错误的ERR!上面可能有额外的日志记录输出。

     

npm ERR!请在任何支持请求中包含以下文件:   错误的ERR! C:\ Users \ Fernando \ Google Drive \ TCC_Fernando_Felipe \ Controller \ controller \ npm-debug.log

服务器端的代码是:

controller.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a controller');
});

/*
 * POST to adduser.
 */
**router.post('/addagent', function(req, res) {
    var db = req.db;
    var collection = db.get('controller');
    var agents = req.body.agents;

    if(agents.length && agents.length >0)
    {
         for(var i=0; i < agents.length; ++i){
                var cAgent = agents[i];

                collection.insert(cAgent, function(err, result){
                res.send(
                    (err === null) ? { msg: '' } : { msg: err }
                );
            });
        }
    }


});**

module.exports = router;

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Added for database connection
var mongo=require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/controller');


var routes = require('./routes/index');
var users = require('./routes/users');
var controller = require('./routes/controller')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});


app.use('/', routes);
app.use('/users', users);
app.use('/controller',controller);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

错误似乎是由下面的行块引起的。我不知道为什么,因为res变量只在那一刻被访问。

res.send(
                    (err === null) ? { msg: '' } : { msg: err }
                );

2 个答案:

答案 0 :(得分:0)

我发现了问题,就是那个,试图多次发送res.send()。

答案 1 :(得分:0)

您使用res.send()多次发送数据。因此发生此错误。 试试这个:

router.post('/addagent', function(req, res) {
var db = req.db;
var collection = db.get('controller');
var agents = req.body.agents;
var count=1;
if(agents.length && agents.length >0)
{
     for(var i=0; i < agents.length; ++i){
            var cAgent = agents[i];

            collection.insert(cAgent, function(err, result){
            if(err)
               res.send({ msg: err });
            else{
              count++;
              if(count== agents.length){
                 res.send(
                     { msg: '' }
                 );
              }
            }
        });
    }
}


});