Gusttavo13
Gusttavo13
CDCloudflare Developers
Created by Gusttavo13 on 2/4/2025 in #workers-help
I can't use fetch in workers
Hi, I'm having a problem with fetching external links, I'm using Worker and on site the fetch works for external links but when I deploy to Cloudflare, the fetch stops working That's my code
interface Env {
MY_BUCKET: R2Bucket;
CREATOR: DurableObjectNamespace<CreatorDO>
}

export class CreatorDO extends DurableObject {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
}

async fetch(request: Request): Promise<Response> {
if (request.method !== "POST") {
return new Response("Method not allowed", { status: 405 });
}
try {

const requestData = await request.json();
const { url, body }: any = requestData;

if (!url) {
return new Response("Missing URL in request body", { status: 400 });
}

const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body)
});
if (response.ok) {
return new Response(JSON.stringify(response.json()), {
headers: { "Content-Type": "application/json" },
});
} else {
return new Response(`CreatorDO Error: ${ await response.text()}`, {
status: 500,
});
}
} catch (error: any) {
return new Response(`CreatorDO Error: ${error.message}`, {
status: 500,
});
}
}
}
interface Env {
MY_BUCKET: R2Bucket;
CREATOR: DurableObjectNamespace<CreatorDO>
}

export class CreatorDO extends DurableObject {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
}

async fetch(request: Request): Promise<Response> {
if (request.method !== "POST") {
return new Response("Method not allowed", { status: 405 });
}
try {

const requestData = await request.json();
const { url, body }: any = requestData;

if (!url) {
return new Response("Missing URL in request body", { status: 400 });
}

const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body)
});
if (response.ok) {
return new Response(JSON.stringify(response.json()), {
headers: { "Content-Type": "application/json" },
});
} else {
return new Response(`CreatorDO Error: ${ await response.text()}`, {
status: 500,
});
}
} catch (error: any) {
return new Response(`CreatorDO Error: ${error.message}`, {
status: 500,
});
}
}
}
2 replies