Skip to content

Commit

Permalink
Added CORS header to responses for the new endpoints.
Browse files Browse the repository at this point in the history
These issue simple requests so they don't need preflight, but they do need the
relevant header. Also added it to the error/redirect responses as well so that
web apps get a nicer error message than "CORS failure".
  • Loading branch information
LTLA committed May 9, 2024
1 parent ac09113 commit 5f58f49
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
22 changes: 17 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,28 @@ router.get("/list", read.listFilesHandler);
/*** Setting up the listener ***/

router.get("/", () => {
return new Response(null, { headers: { "Location": "https://artifactdb.github.io/gypsum-worker" }, status: 301 })
return new Response(null, {
headers: {
"Location": "https://artifactdb.github.io/gypsum-worker",
"Access-Control-Allow-Origin": '*'
},
status: 301
})
})

router.all('*', request => {
const u = request.url;
const pattern = /([^:])(\/\/+)/g;
if (u.match(pattern)) {
return new Response(null, { headers: { "Location": u.replace(pattern, "$1/") }, status: 301 })
return new Response(null, {
headers: {
"Location": u.replace(pattern, "$1/"),
'Access-Control-Allow-Origin': '*'
},
status: 301
})
}
return http.errorResponse("no such endpoint", 404);
return http.errorResponse("no such endpoint", 404, { 'Access-Control-Allow-Origin': '*' });
})

export default {
Expand All @@ -120,9 +132,9 @@ fetch(request, env, context) {
.fetch(request, env, nonblockers)
.catch(error => {
if (error instanceof http.HttpError) {
return http.errorResponse(error.message, error.statusCode);
return http.errorResponse(error.message, error.statusCode, { 'Access-Control-Allow-Origin': '*' });
} else {
return http.errorResponse(error.message, 500);
return http.errorResponse(error.message, 500, { 'Access-Control-Allow-Origin': '*' });
}
});

Expand Down
3 changes: 2 additions & 1 deletion src/read.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ function createHeaders(payload) {
headers.set('etag', payload.httpEtag);
headers.set('Last-Modified', payload.uploaded.toUTCString());
headers.set("Content-Length", payload.size);
headers.set("Access-Control-Allow-Origin", "*");
return headers;
}

Expand Down Expand Up @@ -40,5 +41,5 @@ export async function listFilesHandler(request, env, nonblockers) {
}
let collected = [];
await s3.listApply(prefix, x => collected.push(x), env, { trimPrefix: false, stripTrailingSlash: false, local: !recursive });
return new http.jsonResponse(collected, 200);
return new http.jsonResponse(collected, 200, { "Access-Control-Allow-Origin": "*" });
}

0 comments on commit 5f58f49

Please sign in to comment.