实现的步骤如下
在workers中新创建一个应用程序
代码如下:
addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { let url = new URL(request.url); // 设置请求头 let modifiedHeaders = new Headers(request.headers); modifiedHeaders.set('Host', 'api.openai.com'); modifiedHeaders.set('Authorization', 'Bearer sk-Jzc**********pYwuI0VsdLI'); modifiedHeaders.set('X-Real-IP', request.headers.get('cf-connecting-ip')); modifiedHeaders.set('X-Forwarded-For', request.headers.get('cf-connecting-ip')); modifiedHeaders.set('REMOTE-HOST', request.headers.get('cf-connecting-ip')); modifiedHeaders.set('Upgrade', request.headers.get('Upgrade')); modifiedHeaders.set('Connection', request.headers.get('Connection')); let newRequest = new Request('https://api.openai.com' + url.pathname, { method: request.method, headers: modifiedHeaders, body: request.body }); let response = await fetch(newRequest); // 设置响应头 let responseHeaders = new Headers(response.headers); if (url.pathname.match(/\.(gif|png|jpg|css|js|woff|woff2)$/)) { responseHeaders.set('Cache-Control', 'public, max-age=60'); // 1 minute cache } else { responseHeaders.set('Cache-Control', 'no-cache'); } return new Response(response.body, { status: response.status, statusText: response.statusText, headers: responseHeaders }); }
在Custom Domains添加一个二级域名
该域名需托管在同一个cloudflare账户下面
在custom domains添加域名成功之后,访问该域名如果出现如下代码则说明反代成功!
{ "error": { "message": "Invalid URL (GET /)", "type": "invalid_request_error", "param": null, "code": null } }
原创文章,作者:朋远方,如若转载,请注明出处:https://caovan.com/miaoyongcloudflaredeworkersgongnengfanxiangdailiopenaideapijiekou/.html