Darkbound
Darkbound

Reputation: 3434

Nextjs ERR_HTTP_HEADERS_SENT in POST handler, from a GET request

So I am making a simple route for my app, which basically, calls another server and returns the data back to me (since CORS is not enabled, I cant do it from the frontend atm).

const getBotState: NextApiHandler = async (req, res) => {
  console.log(req.method);

  switch (req.method) {
    case 'GET':
      try {
        res.status(200).json({ someData: "hi get" });
      } catch (e) {
        console.log(e);
        res.status(404).json({ err: e });
      }
    case 'POST':
      try {    
        res.status(200).json({ someData: "hi post" }); // this is the line that breaks it
      } catch (e) {
        console.log('post error');
        console.log(e);
        res.status(404).json({ err: e });
      }
    default:
  }
};

export default getBotState;

The problems started after I added the POST case.

If I comment out the res.status.... line, the error will go away, but I am making ONLY GET requests currently to this API endpoint, I am not making POST requests at all, and yet, the catch block in the POST case is what triggers the error.

Upvotes: 0

Views: 91

Answers (1)

Nicholas
Nicholas

Reputation: 2863

switch has a unique attribute and its attribute is its ability to 'fall-through' and access the next case statement. This is by design, every programming language does this.

How to fix this? Add a break.

const getBotState: NextApiHandler = async (req, res) => {
  console.log(req.method);

  switch (req.method) {
    case 'GET':
      try {
        res.status(200).json({ someData: "hi get" });
      } catch (e) {
        console.log(e);
        res.status(404).json({ err: e });
      }
      break;

    case 'POST':
      try {    
        res.status(200).json({ someData: "hi post" }); // this is the line that breaks it
      } catch (e) {
        console.log('post error');
        console.log(e);
        res.status(404).json({ err: e });
      }
      break;

    default:
  }
};

export default getBotState;

And then you're done!

From MDN Docs:

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement. The break statement is not required if a return statement precedes it.

Upvotes: 1

Related Questions