搭建自己的无服务器随机图片接口
效果图
api地址:https://image.hgtrojan.news/api
介绍
使用 Cloudflare Workers 部署,无需服务器,直接复制我的代码即可使用。如果想要随机返回自己设定的图片,只需修改 返回图片组(imageUrls)的地址即可。
📌 代码逻辑:
- 提供一个 API 端点(/api),监听请求。
- 当访问 /api 时,随机返回 返回图片组 中的一张图片。
- 缓存优化(如果希望每次请求都返回最新内容,可将缓存时间设为 0)。
- 跨域访问优化,确保不同环境都能正常调用。
⚙️ 关键优化点:
✅ Content-Type: 确保返回的图片类型与原始图片一致。
✅ Cache-Control: public, max-age=3600 → 浏览器缓存 1 小时(3600 秒)。
✅ Access-Control-Allow-Origin: * → 允许所有域访问,解决 CORS 跨域问题。
✅ CDN-Cache-Control: public, max-age=86400 → CDN 允许缓存 24 小时(86400 秒),提升访问速度。
代码
// 内置的图片URL列表
const imageUrls = [
'https://w.wallhaven.cc/full/yx/wallhaven-yxdvjx.png',
'https://w.wallhaven.cc/full/6o/wallhaven-6oek56.jpg',
'https://w.wallhaven.cc/full/z8/wallhaven-z8ppgo.jpg',
'https://w.wallhaven.cc/full/ey/wallhaven-eyz5k8.jpg',
'https://w.wallhaven.cc/full/4g/wallhaven-4gmdqq.jpg',
'https://w.wallhaven.cc/full/k7/wallhaven-k7lr31.png',
'https://w.wallhaven.cc/full/o5/wallhaven-o5l33l.jpg',
'https://w.wallhaven.cc/full/nk/wallhaven-nkxvr6.jpg',
'https://w.wallhaven.cc/full/k7/wallhaven-k7k1q1.jpg',
'https://w.wallhaven.cc/full/q2/wallhaven-q2o275.jpg',
'https://w.wallhaven.cc/full/q6/wallhaven-q6mz2q.jpg',
'https://w.wallhaven.cc/full/o3/wallhaven-o39vd7.jpg',
'https://w.wallhaven.cc/full/yx/wallhaven-yx631d.png',
'https://w.wallhaven.cc/full/1p/wallhaven-1pvyz3.jpg',
'https://w.wallhaven.cc/full/o5/wallhaven-o5q7o9.jpg',
'https://w.wallhaven.cc/full/9d/wallhaven-9dveo1.jpg',
'https://w.wallhaven.cc/full/yx/wallhaven-yx6l7d.jpg',
'https://w.wallhaven.cc/full/yx/wallhaven-yx69mx.jpg',
'https://w.wallhaven.cc/full/3l/wallhaven-3lvy23.jpg',
'https://w.wallhaven.cc/full/gp/wallhaven-gp6kz3.jpg',
'https://w.wallhaven.cc/full/o5/wallhaven-o5qwl7.jpg',
'https://w.wallhaven.cc/full/jx/wallhaven-jxpj9m.jpg',
'https://w.wallhaven.cc/full/m3/wallhaven-m352lm.jpg'
];
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
if (url.pathname === '/api') {
try {
// 随机选择图片URL
const randomIndex = Math.floor(Math.random() * imageUrls.length);
const targetUrl = imageUrls[randomIndex];
// 请求图片数据
const imageResponse = await fetch(targetUrl);
// 创建新的响应对象并添加CORS头
return new Response(imageResponse.body, {
status: imageResponse.status,
headers: {
'Content-Type': imageResponse.headers.get('Content-Type'),
'Cache-Control': 'public, max-age=3600',
'Access-Control-Allow-Origin': '*',
// 可选:添加CDN缓存头
'CDN-Cache-Control': 'public, max-age=86400'
}
});
} catch (error) {
// 错误处理
return new Response('Image fetch failed', {
status: 502,
headers: { 'Content-Type': 'text/plain' }
});
}
}
return new Response('Not Found', {
status: 404,
headers: { 'Content-Type': 'text/plain' }
});
}
打赏: 支付宝
本人所有文章均为技术分享,均用于防御为目的的记录,所有操作均在实验环境下进行,请勿用于其他用途,否则后果自负。 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!