Nuno
Nuno
CDCloudflare Developers
Created by Nuno on 3/6/2024 in #workers-help
Redirect not working when transforming via Workers onError event
Hi folks, I have a worker that resizes images; everything works well except when the animated GIF is too large, which returns an error. I'm trying to redirect upon encountering an error, but without success. What I'm doing wrong? The code:
async function handleRequest(request) {
let url = new URL(request.url);
let options = { cf: { image: { onerror: 'redirect' }}};

if (url.searchParams.has('width')) {
options.cf.image.width = url.searchParams.get('width');
}

if (url.searchParams.has('fit')) {
options.cf.image.fit = url.searchParams.get('fit');
}

if (url.searchParams.has('height')) {
options.cf.image.height = url.searchParams.get('height');
}

const accept = request.headers.get('Accept');
if (/image\/avif/.test(accept)) {
options.cf.image.format = 'avif';
} else if (/image\/webp/.test(accept)) {
options.cf.image.format = 'webp';
}

const imagePath = url.pathname.slice(1);
if (!imagePath) {
return new Response('No image path specified', { status: 400 });
}

const imageRequest = new Request(`https://pub-8eca27df6a304971abd1fe716bc29b.r2.dev/files/${imagePath}`, { headers: request.headers });

const response = await fetch(imageRequest, options);

return new Response(response.body, { status: response.status, headers: response.headers });
}
async function handleRequest(request) {
let url = new URL(request.url);
let options = { cf: { image: { onerror: 'redirect' }}};

if (url.searchParams.has('width')) {
options.cf.image.width = url.searchParams.get('width');
}

if (url.searchParams.has('fit')) {
options.cf.image.fit = url.searchParams.get('fit');
}

if (url.searchParams.has('height')) {
options.cf.image.height = url.searchParams.get('height');
}

const accept = request.headers.get('Accept');
if (/image\/avif/.test(accept)) {
options.cf.image.format = 'avif';
} else if (/image\/webp/.test(accept)) {
options.cf.image.format = 'webp';
}

const imagePath = url.pathname.slice(1);
if (!imagePath) {
return new Response('No image path specified', { status: 400 });
}

const imageRequest = new Request(`https://pub-8eca27df6a304971abd1fe716bc29b.r2.dev/files/${imagePath}`, { headers: request.headers });

const response = await fetch(imageRequest, options);

return new Response(response.body, { status: response.status, headers: response.headers });
}
29 replies