Search code examples
javascriptnode.jsapiexpress

express Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


I am trying to do a get request but it keeps failing on app.js res.json line.

app.js

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  res.status(err.status || 500);
  res.json({ error: err.message });
});

model

const fs = require("fs");
const fileName = "./seatData.json";
const file = require(fileName);

const Seat = function(seat) {
  this.seat = seat.seat;
  this.seatNumber = seat.seatNumber;
  this.price = seat.price;
  this.available = seat.available;
  this.disabilityAccessible = seat.disabilityAccessible;
};

Seat.findSeat = seatNumber => {
  return file.find(obj => obj.seatNumber === seatNumber);
};

Seat.getSeatByNumber = function(seatNumber, result) {
  this.seat = this.findSeat(seatNumber);
  if (Object.keys(this.seat).length > 0) {
    result(null, this.seat);
  } else {
    result({ error: true, message: "Seat not found" });
  }
};

Seat.bookSeat = function(seatNumber, result) {
  this.seat = this.findSeat(seatNumber);
  if (this.seat === undefined || Object.keys(this.seat).length === 0) {
    result({ error: true, message: "Seat not found" });
  }
  const newSeatData = file.map(row => {
    if (row.seatNumber === seatNumber) {
      row.available = false;
      this.seat = row;
    }
    return row;
  });
  fs.writeFile("./seatData.json", newSeatData, "utf-8", function(err) {
    if (err) {
      result({ error: true, message: "failed to update booking" });
    }
  });

  result(null, this.seat);
};

module.exports = Seat;

route

router.get(
  "/bookSeat/:seatNumber",
  [
    check("seatNumber")
      .exists(true)
      .withMessage("Must pass seatNumber")
      .matches(/^[0-9][a-z]$/i)
      .withMessage("must start with a number(0-9) and end with a letter")
  ],
  actions.update_seat
);

controller

exports.update_seat = (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    res.status(422).json({ error: true, message: errors.array() });
  }
  console.log(errors);
  Seat.bookSeat(req.params.seatNumber, (err, seat) => {
    if (err) res.json(err);
    else res.json(seat);
  });
};

I am trying to call bookSeat https://codesandbox.io/s/elucidate-api-fokd8


Solution

  • After an error occured, you still go on with execution:

     if (!errors.isEmpty()) {
      res.status(422).json({ error: true, message: errors.array() });
      return; // <<!!
     }