[ERR_HTTP_HEADERS_SENT] Error

I am working on the Timestamp Microservice project and I keep running into this error with only one res.json response and I am confused on what I am doing wrong. Here is my Express router function.

app.get("/api/:date?", (req, res) => {
  let final_res;
  let date = new Date(req.params.date);
  if (date == "Invalid Date"){
  
    if (req.params.date === undefined){
      let cur_date = new Date();
      final_res = {unix: cur_date.getTime(), "utc": cur_date.toUTCString()};
      
    } else {
      if (parseInt(req.params.date) !== "NaN"){
        
        let utc_date = new Date(); utc_date.setMilliseconds(parseInt(req.params.date));
        final_res = {unix: utc_date.getTime(), "utc": utc_date.toUTCString()};
        
      } else {
        final_res = {"error": "Invalid Date"};
      }
    }
    
  } else {
    final_res = {unix: date.getTime(), "utc": date.toUTCString()}
  }
  res.json(final_res);
});

I don’t know what I am doing wrong and would appreciate your help.

Please always post a link to your full project code.

The error is not coming from the code above. The error is coming from:

app.get("/api/1451001600000", (req, res, next) => {
  res.json({"unix":1451001600000, "utc":"Fri, 25 Dec 2015 00:00:00 GMT"});
  next();
});

Your use of next() here is allowing the next middleware app.get("/api/:date?", (req, res) => { to run. Hence, you end up trying to send JSON twice.

You really should delete this entire route as it would be considered hardcoding the correct response instead of having your app create the correct response for the 4th user story/test. All your logic to handle the 4th test can take place in the app.get("/api/:date?" route.

I had no idea that other function was breaking things. Thank you a lot.