Cloudflare Worker API interaction works on local deployment but not live - getting Error 502 Bad Gateway

Hello Everyone

I’m a new to Cloudflare and stuck at a problem. I have created a Cloudflare worker that interacts with an external API (HuggingFace) via a POST request. It works great on localhost but as soon as I deploy on production and try to invoke the endpoint, The API returns 502 Bad Gateway.

The Worker is supposed to interact with an external API to fetch some data and return it in JSON format. Here’s what my code looks like:

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  // Ensure that the request is a POST request

  try {
    // Parse the request body as text
    const requestBody = await request.text();
    // Make a POST request to the external API with the same body
    const apiUrl = "https://api-inference.huggingface.co/models/roberta-base-openai-detector";
    const apiResponse = await fetch(apiUrl, {
      method: "POST",
      body: JSON.stringify(requestBody),
      headers: { "Content-Type": "application/text", "Authorization": "Bearer " + process.env.API_TOKEN },
    });

    // Return the response from the external API as the response from the Cloudflare worker
    return new Response(await apiResponse.text(), {
      status: apiResponse.status,
      headers: { "Content-Type": "application/json" },
    });
  } catch (error) {
    // If there is an error, return a 500 error response
    return new Response("Internal Server Error", { status: 500 });
  }
}

When I test this code locally using Wrangler, everything works as expected. However, when I publish the Worker and try to access it live using the generated URL, I get a 502 Bad Gateway error. I’ve tried various troubleshooting steps such as checking my API key, making sure the external API is accessible, and checking the Cloudflare dashboard for any errors, but I haven’t been able to identify the root cause of the issue.

Has anyone else run into a similar issue with Workers where the code works locally but not when deployed live? If so, do you have any suggestions for how to fix it? Any help would be greatly appreciated!

Thank you in advance.