-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudflare-http-proxy.js
More file actions
44 lines (37 loc) · 1.16 KB
/
Copy pathcloudflare-http-proxy.js
File metadata and controls
44 lines (37 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const ALLOWED_ORIGINS = [
"http://localhost:5173",
"https://openapi-ui.netlify.app",
];
const corsHeaders = {
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "http://localhost:5173",
};
const originHeader = "Access-Control-Allow-Origin";
function getCorsHeaders(req) {
const origin = req.headers.get("Origin");
const headers = { ...corsHeaders };
if (ALLOWED_ORIGINS.includes(origin)) {
headers[originHeader] = origin;
}
return headers;
}
// this should match the `urlHeader` of HttpProxyContext
const headerName = "x-target-url";
export default {
async fetch(req) {
const { method, body } = req;
if (method === "OPTIONS") {
return new Response(null, { headers: getCorsHeaders(req), status: 204 });
}
const targetUrl = req.headers.get(headerName);
const headers = new Headers(req.headers);
headers.delete(headerName);
const response = await fetch(targetUrl, { method, body, headers });
const resp = new Response(response.body, response);
Object.entries(getCorsHeaders(req)).forEach(([k, v]) => {
resp.headers.set(k, v);
});
return resp;
},
};