Cũng như topic Code js upload ảnh sử dụng API Cloudinary , cùng sự tò mò của @copecute thì topic này sẽ là câu trả lời.
Ý tưởng ở đây là mình sử dụng trung gian qua Cloudflare với Proxy. Về khoản chức năng thì chỉ cần đến:
- Imgur cliend ID;
- Fake user-agent;
- CORS headers;
Code phía Cloudflare:
Vậy url có query là:
Code phía client:https://demonn.novawap.com/js-imgurclient
Ý tưởng ở đây là mình sử dụng trung gian qua Cloudflare với Proxy. Về khoản chức năng thì chỉ cần đến:
- Imgur cliend ID;
- Fake user-agent;
- CORS headers;
Code phía Cloudflare:
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
// Thêm CORS headers cho mọi response
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
// Handle preflight OPTIONS
if (request.method === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
if (request.method !== "POST") {
return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
status: 405,
headers: { "Content-Type": "application/json", ...corsHeaders },
});
}
const url = new URL(request.url);
const clientId = url.searchParams.get("clientId");
if (!clientId) {
return new Response(JSON.stringify({ success: false, error: "Missing clientId query parameter" }), {
status: 400,
headers: { "Content-Type": "application/json", ...corsHeaders },
});
}
const formData = await request.formData();
const image = formData.get("image");
if (!image) {
return new Response(JSON.stringify({ success: false, error: "No image provided" }), {
status: 400,
headers: { "Content-Type": "application/json", ...corsHeaders },
});
}
const imgurForm = new FormData();
imgurForm.append("image", image);
const userAgent = request.headers.get("User-Agent") || "Mozilla/5.0";
const imgurResponse = await fetch("https://api.imgur.com/3/image", {
method: "POST",
body: imgurForm,
headers: {
"Authorization": `Client-ID ${clientId}`,
"User-Agent": userAgent,
},
});
const data = await imgurResponse.json();
// Forward nguyên response từ Imgur (kể cả lỗi)
return new Response(JSON.stringify(data), {
status: imgurResponse.status,
headers: {
"Content-Type": "application/json",
...corsHeaders
},
});
}Vậy url có query là:
https://pagecuaban.workers.dev?clientId=...Code phía client:https://demonn.novawap.com/js-imgurclient