502 Bad Gateway When Accessing a Model via Cloudflare Worker

Hello Everyone

I’m a new to HugginFace and stuck at a problem. I have created a CloudFlare worker that interacts with Roberta Base Open AI Detector. It works great on localhost but as soon as I deploy on production and try to invoke the endpoint, HuggingFace API returns 502 Bad Gateway.

It may sound like a cloudflare problem, but I have tried multiple other endpoints that are working fine.

Here’s the code I’m using

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 });
  }
}

Kindly help