Skip to content

Instantly share code, notes, and snippets.

@erbanku
Created May 26, 2023 02:06
Show Gist options
  • Save erbanku/7abefe9836212de858caf531da83cd3f to your computer and use it in GitHub Desktop.
Save erbanku/7abefe9836212de858caf531da83cd3f to your computer and use it in GitHub Desktop.
OpenAI API Proxy on Cloudflare Workers
const TELEGRAPH_URL = 'https://api.openai.com';
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url);
const headers_Origin = request.headers.get("Access-Control-Allow-Origin") || "*"
url.host = TELEGRAPH_URL.replace(/^https?:\/\//, '');
const modifiedRequest = new Request(url.toString(), {
headers: request.headers,
method: request.method,
body: request.body,
redirect: 'follow'
});
const response = await fetch(modifiedRequest);
const modifiedResponse = new Response(response.body, response);
// 添加允许跨域访问的响应头
modifiedResponse.headers.set('Access-Control-Allow-Origin', headers_Origin);
return modifiedResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment