Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
arielhernandezcl committed Feb 26, 2024
1 parent dbce7b1 commit 03d159c
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,30 @@

FixCors es una herramienta simple que te ayuda a solucionar los errores de CORS (Cross-Origin Resource Sharing) que pueden ocurrir al consumir APIs desde diferentes dominios. Con FixCors, podrás:

- Consumir una API y evitar los errores de cors en el navegador

- Evitar instalar o realizar configuraciones extrañas


## Como Usar FixCors

Para usar FixCors es muy facil.

Coloca lo siguiente antes de la url de la API que deseas consumir

```html
https://fixcors.site/?api=

```
La url completa quedara de la siguiente manera

```html
https://fixcors.site/?api=https://apps.bolchile.com/api/v1/dolarstatd2

```
Asi de simple


## Licencia

[![GPLv3 License](https://img.shields.io/badge/License-GPL%20v3-yellow.svg)](https://opensource.org/licenses/)
Expand Down
72 changes: 72 additions & 0 deletions worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
export default {
async fetch(request) {
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
};

const PROXY_ENDPOINT = "/";


async function handleRequest(request) {
const url = new URL(request.url);
let apiUrl = url.searchParams.get("api");

request = new Request(apiUrl, request);
request.headers.set("Origin", new URL(apiUrl).origin);
let response = await fetch(request);
response = new Response(response.body, response);
response.headers.set("Access-Control-Allow-Origin", url.origin);
response.headers.append("Vary", "Origin");

return response;
}

async function handleOptions(request) {
if (
request.headers.get("Origin") !== null &&
request.headers.get("Access-Control-Request-Method") !== null &&
request.headers.get("Access-Control-Request-Headers") !== null
) {
return new Response(null, {
headers: {
...corsHeaders,
"Access-Control-Allow-Headers": request.headers.get(
"Access-Control-Request-Headers"
),
},
});
} else {
return new Response(null, {
headers: {
Allow: "GET, HEAD, POST, OPTIONS",
},
});
}
}

const url = new URL(request.url);
if (url.pathname.startsWith(PROXY_ENDPOINT)) {
if (request.method === "OPTIONS") {
return handleOptions(request);
} else if (
request.method === "GET" ||
request.method === "HEAD" ||
request.method === "POST"
) {

return handleRequest(request);
} else {
return new Response(null, {
status: 405,
statusText: "Method Not Allowed",
});
}
} else {
return;
}
},
};

//se modifica worker de cloudflare y se adapta para recibir solo url de la api de destino como parametro

0 comments on commit 03d159c

Please sign in to comment.