Files
CloudFlare-ImgBed/functions/api/fetchRes.js
2024-08-23 11:46:22 +08:00

38 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export async function onRequest(context) {
// 获取请求体中URL的内容判断是否为图片或视频如果是则返回否则返回错误信息
const {
request,
env,
params,
waitUntil,
next,
data
} = context;
//如果是OPTIONS请求返回允许的方法
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
}
})
}
const jsonRequest = await request.json();
const url = jsonRequest.url;
if (url === undefined) {
return new Response('URL is required', { status: 400 })
}
const response = await fetch(url);
const contentType = response.headers.get('content-type');
if (contentType.startsWith('image') || contentType.startsWith('video')) {
//增加跨域头后返回
const headers = new Headers(response.headers);
headers.set('Access-Control-Allow-Origin', '*');
return new Response(response.body, {
headers: headers
})
} else {
return new Response('URL is not an image or video', { status: 400 })
}
}