Sunday, 16 April 2017

GET /dishes 500 4.732 ms - - Error: Can't set headers after they are sent

I am new to Node.js,and so far I have managed to install Express. Now I have three js files,that handle CRUD requests to a localserver.

ie.

localhost:3000/dishes
localhost:3000/promotions

etc. However, when I am doing a simple get request in postman,I get this error.

GET /dishes 500 8.883 ms - -
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)

I am going to show you my files.

dishRouter.js

//exporing the functionality
module.exports = function (dishRouter, bp) {
dishRouter.use(bp.json()); //using body parser for parsing json from body 
content
//code for url '/'
dishRouter.route('/').all(function (req, res, next) {
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        next();
    })
    //setting up code for get request
    .get(function (req, res, next) {
        res.end('Will send all the dishes to you!');
    })
    //setting up code for post request
    .post(function (req, res, next) {
        res.end('Will add the dish: ' + req.body.name + ' with details: ' + 
    req.body.description);
    })
    //setting up code for delete request
    .delete(function (req, res, next) {
        res.end('Deleting all dishes');
    });
//code for url with specific ids
dishRouter.route('/:dishId')
    .all(function (req, res, next) {
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        next();
    })
    //setting up code for get request
    .get(function (req, res, next) {
        res.end('Will send details of the dish: ' + req.params.dishId + ' to you!');
    })
    //setting up code for put request
    .put(function (req, res, next) {
        res.write('Updating the dish: ' + req.params.dishId + '\n');
        res.end('Will update the dish: ' + req.body.name +
            ' with details: ' + req.body.description);
    })
    //setting up code for delete request
    .delete(function (req, res, next) {
        res.end('Deleting dish: ' + req.params.dishId);
    });

 };

promoRouter.js

   //exporting the functionality
    module.exports = function (promoRouter, bp) {
        promoRouter.use(bp.json()); //using body parser for parsing json 
    from body content
        //code for url '/'
        promoRouter.route('/').all(function (req, res, next) {
                res.writeHead(200, { //writing header
                    'Content-Type': 'text/plain'
                });
                next();
            })
            //setting up code for get request
            .get(function (req, res, next) {
                res.end('Will send all the promotions to you!');
            })
            //setting up code for post request
            .post(function (req, res, next) {
                res.end('Will add the promotion: ' + req.body.name + ' with 
    details: ' + req.body.description);
            })
            //setting up code for delete request
            .delete(function (req, res, next) {
                res.end('Deleting all promotions');
            });
        //code for url with specific ids
        promoRouter.route('/:promoId')
            .all(function (req, res, next) {
                res.writeHead(200, {
                    'Content-Type': 'text/plain'
                });
                next();
            })
            //setting up code for get request
            .get(function (req, res, next) {
                res.end('Will send details of the promotion: ' + 
    req.params.promoId + ' to you!');
            })
            //setting up code for put request
            .put(function (req, res, next) {
                res.write('Updating the promotion: ' + req.params.promoId + '\n');
                res.end('Will update the promotion: ' + req.body.name +
                    ' with details: ' + req.body.description);
            })
            //setting up code for delete request
            .delete(function (req, res, next) {
                res.end('Deleting promotion: ' + req.params.promoId);
            });
    };

leaderRouter.js

//exporing the functionality
module.exports = function (leaderRouter, bp) {
leaderRouter.use(bp.json()); //using body parser for parsing json from body 
 content
//code for url '/'
leaderRouter.route('/').all(function (req, res, next) {
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        next();
    })
    //setting up code for get request
    .get(function (req, res, next) {
        res.end('Will send all the leaders to you!');
    })
    //setting up code for post request
    .post(function (req, res, next) {
        res.end('Will add the leader: ' + req.body.name + ' with details: ' 
   + req.body.description);
    })
    //setting up code for delete request
    .delete(function (req, res, next) {
        res.end('Deleting all leaders');
    });
//code for url with specific ids
leaderRouter.route('/:leaderId')
    .all(function (req, res, next) {
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        next();
    })
    //setting up code for get request
    .get(function (req, res, next) {
        res.end('Will send details of the leader: ' + req.params.leaderId + ' to you!');
    })
    //setting up code for put request
    .put(function (req, res, next) {
        res.write('Updating the leader: ' + req.params.leaderId + '\n');
        res.end('Will update the leader: ' + req.body.name +
            ' with details: ' + req.body.description);
    })
    //setting up code for delete request
    .delete(function (req, res, next) {
        res.end('Deleting leader: ' + req.params.leaderId);
    });
 };

The above 3 files are inside the routes folder. And finally,I have 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');

    var routes = require('./routes/index');
    var users = require('./routes/users');
    var dishRouter = require('./routes/dishRouter');
    var promoRouter = require('./routes/promoRouter');
    var leaderRouter = require('./routes/leaderRouter');

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

    app.use('/', routes);
    app.use('/users', users);
    app.use('/dishes',dishRouter);
    app.use('/promotions',promoRouter);
    app.use('/leadership',leaderRouter);

    // 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;

Any ideas why I am getting this error? Please advice.

Thanks,

Theo.



via Theo

No comments:

Post a Comment