node.jsexpressapi-keysecret-key

How to get data from an external api that has an api key and a secret key


I have created an api for pulling data from an external api.I have the apikey and the secret key configured in the .env file.

When I test the endpoint, it gives an error that says "Cannot set headers after they are sent to the client".

Also when I console log data in my code I get an error that says "{ status: 'bad', auth: 0, reason: 'Invalid Key' }"

How do I solve this

const apiKey = process.env.API_KEY;
const apiSecret = process.env.API_SECRET;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/insert/data/:start", async (req, res) => {
  let start = parseInt(req.params.start);

  try {
    while (start <= 3) {
      const { default: fetch } = await import("node-fetch");

      const response = await fetch(
        `https://data.co/api/docs/v1?a_id=${start}`,
        {
          headers: {
            Authorization: `Basic ${Buffer.from(
              `${apiKey}:${apiSecret}`
            ).toString("base64")}`,
          },
        }
      );
      if (response.ok) {
        const data = await response.json();
        console.log(data);
        let n = await createNew(data.jsonData);
        res.send({ Created: n });
        return;
      } else {
        const errorData = await response.json();
        throw new Error(
          `Retrieve Failed. API Error: ${JSON.stringify(errorData)}`
        );
      }
    }
  } catch (error) {
    res.status(500).send({ error: error.message });
  }
});

Solution

  • I have identified two issues in the snippet mentioned above.

    Firstly, the code res.send({ Created: n }) is being executed inside the while loop, causing the system to throw an error message stating "Cannot set headers after they are sent to the client". In order to resolve this, it is important to only return the response once per API call.

    Secondly, the error message "{ status: 'bad', auth: 0, reason: 'Invalid Key' }" is likely originating from the data.co endpoint. I recommend double-checking the keys to ensure their validity.