const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
export default async function(req: Request): Promise<Response> {
if (req.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
...corsHeaders,
"Access-Control-Max-Age": "86400",
},
});
}
const incomingUrl = new URL(req.url);
const destUrlString = decodeURIComponent(incomingUrl.pathname.slice(1));
try {
new URL(destUrlString);
} catch (error) {
return new Response(JSON.stringify({ error: "Invalid destination URL" }), {
status: 400,
headers: {
"Content-Type": "application/json",
...corsHeaders,
},
});
}
const headers = new Headers(req.headers);
headers.delete("Host");
const init = {
method: req.method,
headers: headers,
body: req.body,
};
const response = await fetch(destUrlString, init);
return new Response(response.body, {
status: response.status,
headers: {
...response.headers,
...corsHeaders,
},
});
}