Thursday, 18 May 2017

Unhandled rejection Error: Can't set headers after they are sent using Node

I am attempting to render a view using JS, Node, and Express but am getting this error 'Unhandled rejection Error: Can't set headers after they are sent'. I know it's something to do with asynchronous callbacks, but I can't work out exactly how to fix it.

const userController = require('../controllers').user;
const spaceController = require('../controllers').space;

module.exports = (app) => {
  app.get('/', function(req, res) {
      res.render('index.ejs');
  });

  app.post('/users/new', function(req,res){
    userController.create(req,res);
    res.redirect('/');
  });

  app.get('/spaces', function(req, res) {
    var spaces = spaceController.retrieve(req,res);
    res.render('spaces/index.ejs', {spaces});

  });

  app.get('/spaces/new', function(req, res) {
    res.render('spaces/new.ejs');
  });

  app.post('/spaces/new', function(req,res){
    spaceController.create(req,res);
    res.redirect('/spaces');
  });

};

And my controller:

const Space = require('../models').Space;

module.exports = {
  create(req, res) {
    return Space
    .create({
      name: req.body.name,
      description: req.body.description,
      price: req.body.price,
    })
    .then(space => res.status(201).send(space))
    .catch(error => res.status(400).send(error));
  },

  retrieve(req, res) {
    return Space
    .findAll()
    .then(space => {
      if (!space) {
        return res.status(404).send({
          message: 'Space Not Found',
        });
      }
      return res.status(200).send(space);
    })
    .catch(error => res.status(400).send(error));
  },
};

And my view:

<!doctype html>
 <html>
 <head>
     <title>MakersBnB</title>
     <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
     <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
     <style>
         body        { padding-top:80px; }
     </style>
 </head>
 <body>
 <div class="container">

 <div class="col-sm-6 col-sm-offset-3">
   <div class="jumbotron text-center">

     <h1>Book a Space</h1>

<form action="/spaces/new" method="get">
  <button type="submit" class="btn btn-warning btn-lg">List a space</button>

</form>

<div class="spaces">
  <% spaces.each(function(space) { %>
        <ul>
          <li><%= space.name %></a></li>
          <li><%= space.description %></li>
          <li>£ <%= space.price %></li>
        </ul>
        <% });%>
</div>


 </div>

 </div>
 </body>
 </html>



via Paula Muldoon

No comments:

Post a Comment