gen / routes /proxy.js
AnesKAM's picture
Create routes/proxy.js
96e6ae0 verified
Raw
History Blame Contribute Delete
1.06 kB
import express from "express";
import fetch from "node-fetch";
const router = express.Router();
// GET /api/img?u=<encoded image url> -> يعيد الصورة من نفس الأصل (يحل CORS للـ canvas)
router.get("/img", async (req, res) => {
try {
const u = req.query.u;
if (!u) return res.status(400).send("missing url");
const url = decodeURIComponent(u);
if (!/^https?:\/\//i.test(url)) return res.status(400).send("bad url");
const r = await fetch(url, {
headers: { "User-Agent": "Mozilla/5.0", Accept: "image/*" },
});
if (!r.ok) return res.status(502).send("fetch failed");
const type = r.headers.get("content-type") || "image/jpeg";
res.setHeader("Content-Type", type);
res.setHeader("Cache-Control", "public, max-age=86400");
res.setHeader("Access-Control-Allow-Origin", "*");
const buf = Buffer.from(await r.arrayBuffer());
res.send(buf);
} catch (err) {
console.error("img proxy error:", err);
res.status(500).send("proxy error");
}
});
export default router;