lugenx/ecohabit

Fix "[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" errors in earth911 mock APIs

Opened this issue · 1 comments

Context

  • We have mock APIs which send a request to the earth911's API and then forward its response to the client
    • /earth911.getPostalData
    • /earth911.searchLocations
    • /earth911.getLocationDetails
  • If you hit any of these API endpoints, with an invalid api_key query parameter, and hit the endpoint again with valid one, you should see the error in the terminal
  • I believe this is because there are missing return statements in the controllers for these endpoints.
  • Example,
router.get("/", async (req, res) => {
  if (req.query.api_key !== "dummykey") {
    res.send({ err: "invalid key" });
  }
  const country = req.query.country;
  const postalCode = req.query.postal_code;

  const API_KEY = process.env.API_KEY;

  try {
    const data = await fetchData(
      `http://api.earth911.com/earth911.getPostalData?api_key=${API_KEY}&country=${country}&postal_code=${postalCode}`
    );

    res.send(data);
  } catch (error) {
    console.log("ERROR: ", error);
  }
});

here, instead of res.send({ err: "invalid key" });, there should be return res.send({ err: "invalid key" });
This will sure that the response is sent and the function call is also over.

If you find this issue on any other endpoint, feel free to fix that as well