Skip to content

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

Description

@vishwaszadte

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions